jQuery 按空格或多个空格分割
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7081958/
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
splitting by white space or multiple white spaces
提问by re1man
Right now I split words by one whitespace and store in an array: var keywds = $("#searchquery").text().split(" ");
现在我用一个空格分割单词并存储在一个数组中: var keywds = $("#searchquery").text().split(" ");
The problem is there can/might be multiple white spaces. For example :
问题是可以/可能有多个空格。例如 :
"hello world"
How would I still have the array = [hello, world]
我怎么还会有数组 = [hello, world]
回答by Felix Kling
Use a regular expression (\s
matches spaces, tabs, new lines, etc.)
使用正则表达式(\s
匹配空格、制表符、新行等)
$("#searchquery").text().split(/\s+/);
or if you want to split on spaces only:
或者如果您只想在空格上拆分:
$("#searchquery").text().split(/ +/);
+
means match one or more of the preceding symbol.
+
表示匹配一个或多个前面的符号。
Further reading:
进一步阅读: