我想我从一些示例代码开始:
var sentence = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.';
// Makes an array with the single chars of the sentence as elements.
sentence = sentence.split('');
// Makes a multi-dimensional array.
var result = sentence.map(function(ch) {
// Using /./ leads to an multi-dimensional array too.
// Each array contains two empty strings as elements.
// => ["", ""]
return ch.split(/. /);
});
result.forEach(function(item, i) {
console.log(item); // [ ["L"], ["o"], ["r"] ... ]
});
我的目的很明确:它是为了制作一个多维数组。每个元素都有句子的一个字符。
我不明白的是所使用的正则表达式。
。代表正则表达式中的任意一个字符。
点(.)后面的空格有什么作用?
此外: 如果我去掉空白并只写/./那么结果也是数组。每个数组包含两个空字符串 ( "")。
我也不清楚这种行为。
任何人都可以解释所描述的正则表达式行为吗?
喜欢添加: 我在这里看到了代码片段... https://davidwalsh.name/write-javascript-promises
位于“链接”部分的底部。
最佳答案
"x".split(/. /)
效果与
相同"x".split(/rabbit/)
它只是收集字符串中不包含分隔符的部分(=整个字符串),然后停止。
"x".split(/./)
收集与 .
不匹配的部分(=空字符串),然后使用分隔符 (=x
),然后附加字符串的其余部分 (这是空的)到结果。
关于javascript - 创建包含字符串的单个字符的数组。这些正则表达式是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39370557/