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 bees 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
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 bees 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
Share
edited Mar 2, 2012 at 14:57
Adamarla
asked Mar 2, 2012 at 14:48
AdamarlaAdamarla
81210 silver badges22 bronze badges
1 Answer
Reset to default 7Splitting won't work if the delimiter should stay in the result, because the delimiter is always consumed.
Use .match
instead:
"This is an example-string to demo what I mean".match(/[^\s-]+-?/g);
// ["This", "is", "an", "example-", "string", "to", "demo", "what", "I", "mean"]
This regexp matches one or more characters that are not spaces/dashes, and an optional dash following it. With the g
flag, all matches are returned.