我如何使用一个正则表达式将字符串拆分为空格,而忽略前面的空格和后面的空格?

时间:2021-03-15 21:40:26

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?

消除这样的空字符是一项微不足道的任务,但如果可能的话,我宁愿在正则表达式中处理它。有人知道我可以用什么正则表达式来实现这个目标吗?

3 个解决方案

#1


85  

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:

注意,以下返回为空:

"   ".match(/\S+/g)

So the best pattern to learn is:

所以最好的学习模式是:

str.match(/\S+/g) || []

#2


31  

" The quick brown fox jumps over the lazy dog. ".trim().split(/\s+/);

敏捷的棕色狐狸跳过了懒狗。“.trim().split(/ \ s + /;

#3


9  

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)

#1


85  

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:

注意,以下返回为空:

"   ".match(/\S+/g)

So the best pattern to learn is:

所以最好的学习模式是:

str.match(/\S+/g) || []

#2


31  

" The quick brown fox jumps over the lazy dog. ".trim().split(/\s+/);

敏捷的棕色狐狸跳过了懒狗。“.trim().split(/ \ s + /;

#3


9  

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)