我通常在JavaScript中使用以下代码来按空格分割字符串。
"The quick brown fox jumps over the lazy dog.".split(/\s+/);
// ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
这当然有效,即使单词之间有多个空白字符。
"The quick brown fox jumps over the lazy dog.".split(/\s+/);
// ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
问题是当我有一个带有前导或尾随空格的字符串时,在这种情况下,生成的字符串数组将在数组的开头和/或结尾包含一个空字符。
" The quick brown fox jumps over the lazy dog. ".split(/\s+/);
// ["", "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog.", ""]
消除这些空字符是一项微不足道的任务,但如果可能的话,我宁愿在正则表达式中处理这个问题。有谁知道我可以用什么正则表达式来实现这个目标?
答案 0 :(得分:102)
如果您对不是空白的位更感兴趣,可以匹配非空格而不是在空格上拆分。
" The quick brown fox jumps over the lazy dog. ".match(/\S+/g);
请注意,以下内容会返回null
:
" ".match(/\S+/g)
所以学习的最佳模式是:
str.match(/\S+/g) || []
答案 1 :(得分:41)
" The quick brown fox jumps over the lazy dog. ".trim().split(/\s+/);
答案 2 :(得分:13)
您可以匹配任何非空格序列,而不是在空格序列中进行拆分:
" The quick brown fox jumps over the lazy dog. ".match(/\S+/g)
答案 3 :(得分:0)
不像其他代码那么优雅,但是很容易理解:
countWords(valOf)
{
newArr[];
let str = valOf;
let arr = str.split(" ");
for (let index = 0; index < arr.length; index++)
{
const element = arr[index];
if(element)
{
this.newArr.push(element);
}
}
this.NumberOfWords = this.newArr.length;
return this.NumberOfWords;
}