我通常在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.", ""]
这是一个简单的任务,以消除这种空字符,但我宁愿照顾这个正则表达式中,如果这是在所有可能的。 有谁知道我可以使用什么样的正则表达式来实现这一目标?
如果您更感兴趣的是那些没有空格位,可以匹配非空白,而不是在空白分裂。
" The quick brown fox jumps over the lazy dog. ".match(/\S+/g);
请注意,以下返回null
:
" ".match(/\S+/g)
所以,最好的学习方式是:
str.match(/\S+/g) || []
" The quick brown fox jumps over the lazy dog. ".trim().split(/\s+/);
相反,在空白序列分割的,可以匹配任何非空白序列:
" The quick brown fox jumps over the lazy dog. ".match(/\S+/g)
不优雅为别人的代码,但很容易理解:
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;
}
文章来源: How do I split a string by whitespace and ignoring leading and trailing whitespace into an array of words using a regular expression?