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]
我怎么还有数组= [你好,世界]
1 个解决方案
#1
47
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:
- MDN -
string.split
- MDN - Regular expressions
- http://www.regular-expressions.info/
MDN - string.split
MDN - 正则表达式
#1
47
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:
- MDN -
string.split
- MDN - Regular expressions
- http://www.regular-expressions.info/
MDN - string.split
MDN - 正则表达式