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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:22:51  来源:igfitidea点击:

splitting by white space or multiple white spaces

jquery

提问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 (\smatches 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:

进一步阅读: