Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splitting by white space or multiple white spaces

Tags:

jquery

Right now I split words by one whitespace and store in an array: 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]

like image 469
re1man Avatar asked Aug 16 '11 16:08

re1man


People also ask

How do you split one or more spaces?

split() method to split a string by one or more spaces. The str. split() method splits the string into a list of substrings using a delimiter.

How do I split a space in Javascript?

To split a string keeping the whitespace, call the split() method passing it the following regular expression - /(\s+)/ . The regular expression uses a capturing group to preserve the whitespace when splitting the string.

How do you split spaces in Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do I know if my string has white space?

Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.


1 Answers

Use a regular expression (\s matches spaces, tabs, new lines, etc.)

$("#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/
like image 176
Felix Kling Avatar answered Sep 25 '22 02:09

Felix Kling