【发布时间】:2016-05-01 21:44:13
【问题描述】:
我正在尝试做这样的事情
function findLongestWord(str) {
var wordContainer = str.split(/\b/) || 0;
document.write(wordContainer);
}
findLongestWord("The quick brown fox jumped over the lazy dog");
但这会返回
The, ,quick, ,brown, ,fox, ,jumped, ,over, ,the, ,lazy, ,dog
但是如果我做这样的事情
function findLongestWord(str) {
var wordContainer = str.split(" ") || 0;
document.write(wordContainer);
}
findLongestWord("The quick brown fox jumped over the lazy dog");
它按预期工作并返回
The,quick,brown,fox,jumped,over,the,lazy,dog
那么为什么在 split 中使用 /\b/ 与使用 " " 不同?
【问题讨论】:
-
\b是单词边界,空格匹配空格。所以,你得到的结果没有什么奇怪的。 -
你的默认情况也是无用的,因为 split 总是会返回一个数组
标签: javascript arrays regex string split