To split on any whitespace (including newlines), you’d use /\s/ with split:
var theArray = theString.split(/\s+/);
\s means “spaces” (e.g., whitespace — including newlines), and + means “one or more“.
To trim whitespace from the beginning and end of the string first, on any modern browser you can use String#trim:
var theArray = theString.trim().split(/\s+/);
If you have to support older browsers, you can use replace:
var theArray = theString.replace(/^\s+|\s+$/g, '').split(/\s+/);
That regex used with replace can use a bit of explanation: http://regex101.com/r/sS0zV3/1
- ^\s+means “any whitespace at the beginning of the string
- |means “or” (as in , “this or that”) (it’s called an “alternation”)
- \s+$means “any whitepsace at the end of the string
Then we replace all occurrences (g) with '' (a blank string).
4
solved Javascript split function to split into array at new line or white space [closed]