Javascript 如何使用正则表达式按空格拆分字符串并忽略前导和尾随空格到单词数组中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14912502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I split a string by whitespace and ignoring leading and trailing whitespace into an array of words using a regular expression?
提问by natlee75
I typically use the following code in JavaScript to split a string by whitespace.
我通常在 JavaScript 中使用以下代码按空格拆分字符串。
"The quick brown fox jumps over the lazy dog.".split(/\s+/);
// ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
This of course works even when there are multiple whitespace characters between words.
即使单词之间有多个空格字符,这当然也有效。
"The quick brown fox jumps over the lazy dog.".split(/\s+/);
// ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
The problem is when I have a string that has leading or trailing whitespace in which case the resulting array of strings will include an empty character at the beginning and/or end of the array.
问题是当我有一个带有前导或尾随空格的字符串时,在这种情况下,结果字符串数组将在数组的开头和/或结尾包含一个空字符。
" The quick brown fox jumps over the lazy dog. ".split(/\s+/);
// ["", "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog.", ""]
It's a trivial task to eliminate such empty characters, but I'd rather take care of this within the regular expression if that's at all possible. Does anybody know what regular expression I could use to accomplish this goal?
消除这种空字符是一项微不足道的任务,但如果可能的话,我宁愿在正则表达式中处理这个问题。有谁知道我可以使用什么正则表达式来实现这个目标?
回答by kennebec
If you are more interested in the bits that are not whitespace, you can match the non-whitespace instead of splitting on whitespace.
如果您对不是空白的位更感兴趣,您可以匹配非空白而不是拆分空白。
" The quick brown fox jumps over the lazy dog. ".match(/\S+/g);
Note that the following returns null:
请注意,以下返回null:
" ".match(/\S+/g)
So the best pattern to learn is:
所以最好的学习模式是:
str.match(/\S+/g) || []
回答by Josh
" The quick brown fox jumps over the lazy dog. ".trim().split(/\s+/);
" The quick brown fox jumps over the lazy dog. ".trim().split(/\s+/);
回答by Gumbo
Instead of splitting at whitespace sequences, you could match any non-whitespace sequences:
您可以匹配任何非空白序列,而不是在空白序列处拆分:
" The quick brown fox jumps over the lazy dog. ".match(/\S+/g)
回答by aris
Not elegant as others code but very easy to understand:
不像其他代码那样优雅但很容易理解:
countWords(valOf)
{
newArr[];
let str = valOf;
let arr = str.split(" ");
for (let index = 0; index < arr.length; index++)
{
const element = arr[index];
if(element)
{
newArr.push(element);
}
}
const NumberOfWords = newArr.length;
return NumberOfWords;
}

