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]
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.
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.
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.
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.
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:
string.split
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With