nat*_*e75 70 javascript regex string whitespace removing-whitespace
我通常在JavaScript中使用以下代码来按空格分割字符串.
"The quick brown fox jumps over the lazy dog.".split(/\s+/);
// ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
Run Code Online (Sandbox Code Playgroud)
这当然可以在单词之间存在多个空白字符时起作用.
"The quick brown fox jumps over the lazy dog.".split(/\s+/);
// ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
Run Code Online (Sandbox Code Playgroud)
问题是当我有一个具有前导或尾随空格的字符串时,在这种情况下,生成的字符串数组将在数组的开头和/或结尾包含一个空字符.
" The quick brown fox jumps over the lazy dog. ".split(/\s+/);
// ["", "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog.", ""]
Run Code Online (Sandbox Code Playgroud)
消除这些空字符是一项微不足道的任务,但如果可能的话,我宁愿在正则表达式中处理这个问题.有谁知道我可以用什么正则表达式来实现这个目标?
ken*_*bec 113
如果您对不是空格的位更感兴趣,则可以匹配非空格而不是在空格上拆分.
" The quick brown fox jumps over the lazy dog. ".match(/\S+/g);
Run Code Online (Sandbox Code Playgroud)
请注意,以下内容返回null
:
" ".match(/\S+/g)
Run Code Online (Sandbox Code Playgroud)
所以最好的学习方式是:
str.match(/\S+/g) || []
Run Code Online (Sandbox Code Playgroud)
Jos*_*osh 42
" The quick brown fox jumps over the lazy dog. ".trim().split(/\s+/);
Gum*_*mbo 15
您可以匹配任何非空白序列,而不是在空格序列中进行拆分:
" The quick brown fox jumps over the lazy dog. ".match(/\S+/g)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
57862 次 |
最近记录: |