![](/img/trans.png)
[英]Regular expression to find and trim (leading and trailing whitespace) first column
[英]How do I split a string by whitespace and ignoring leading and trailing whitespace into an array of words using a regular expression?
我通常在 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)
{
newArr.push(element);
}
}
const NumberOfWords = newArr.length;
return NumberOfWords;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.