How do I split a string by whitespace and ignoring leading and trailing whitespace into an array of words using a regular expression? How do I split a string by whitespace and ignoring leading and trailing whitespace into an array of words using a regular expression? javascript javascript

How do I split a string by whitespace and ignoring leading and trailing whitespace into an array of words using a regular expression?


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) || []


" The quick brown fox jumps over the lazy dog. ".trim().split(/\s+/);


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)