What is the best way to split a string up into an array of ‘words’.
Splitting by whitespace but also by dashes, where a dash becomes part of the previous ‘word’.
Example:
“This is an example-string to
demo what I mean”
[ “This”, “is” , “an” , “example-” , “string” , “to” , “demo” , “what” , “I” , “mean” ]
Edit: I’m an idiot – It is this:
someString.replace(/-/g, "- ").split(/[\s]/); // retain dashes
Splitting won’t work if the delimiter should stay in the result, because the delimiter is always consumed.
Use
.matchinstead:This regexp matches one or more characters that are not spaces/dashes, and an optional dash following it. With the
gflag, all matches are returned.