How do I split a string by whitespace and ignoring leading and trailing whitespace into an array of words using a regular expression?
Solution 1
If you are more interested in the bits that are not whitespace, you can match the non-whitespace instead of splitting on whitespace.
" The quick brown fox jumps over the lazy dog. ".match(/\S+/g);
Note that the following returns null
:
" ".match(/\S+/g)
So the best pattern to learn is:
str.match(/\S+/g) || []
Solution 2
" The quick brown fox jumps over the lazy dog. ".trim().split(/\s+/);
Solution 3
Instead of splitting at whitespace sequences, you could match any non-whitespace sequences:
" The quick brown fox jumps over the lazy dog. ".match(/\S+/g)
Related videos on Youtube
natlee75
Updated on July 05, 2022Comments
-
natlee75 almost 2 years
I typically use the following code in JavaScript to split a string by whitespace.
"The quick brown fox jumps over the lazy dog.".split(/\s+/); // ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
This of course works even when there are multiple whitespace characters between words.
"The quick brown fox jumps over the lazy dog.".split(/\s+/); // ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
The problem is when I have a string that has leading or trailing whitespace in which case the resulting array of strings will include an empty character at the beginning and/or end of the array.
" The quick brown fox jumps over the lazy dog. ".split(/\s+/); // ["", "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog.", ""]
It's a trivial task to eliminate such empty characters, but I'd rather take care of this within the regular expression if that's at all possible. Does anybody know what regular expression I could use to accomplish this goal?
-
DCoder over 11 yearsHorses for courses.
split
is used to split a string, not mutate it. See how to trim a string in JavaScript?. -
Anirudha over 11 yearsunfortunately javascript doesnt support lookbehind and even if you had used lookbehind,there would be space in the first split
-
natlee75 over 11 yearsI never thought of it from that perspective. Thanks for pointing that out!
-
Jacques Koorts about 6 yearscan't you do a trim() before the split?
-
-
natlee75 over 11 yearsThanks for the suggestion. I actually was going to go this route until I remembered that it requires a browser that supports JavaScript 1.8. That's fine for a majority of our users, but we still support older browsers such as Internet Explorer 7 and 8 whose JavaScript engines don't include this functionality.
-
Andy about 8 yearsWatch out,
' '.match(/\S+/g)
returnsnull
instead of[]
! -
Andy about 8 yearsWatch out,
' '.trim().split(/\s+/)
returns[""]
! -
ibodi about 5 yearsI wonder whose solution is faster yours or @Josh 's (if we handle the [""] case).
-
ibodi about 5 yearsI wonder whose solution is faster yours (if we handle the [""] case) or @kennebec 's