Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
85
rated 0 times [  86] [ 1]  / answers: 1 / hits: 67056  / 12 Years ago, sat, february 16, 2013, 12:00:00

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?


More From » regex

 Answers
166

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

[#80188] Thursday, February 14, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryderalfonsos

Total Points: 655
Total Questions: 88
Total Answers: 91

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
ryderalfonsos questions
Mon, Sep 9, 19, 00:00, 5 Years ago
Wed, Feb 13, 19, 00:00, 5 Years ago
Tue, Feb 12, 19, 00:00, 5 Years ago
Fri, Dec 28, 18, 00:00, 6 Years ago
;