I'm trying to match some words from a string but with no success.
Let's say, for example, i have this string:
"word , word , two words, word"
What i'm trying to do is match the words, but without the space from start or end. But it should accept the spaces from in between the words. The array resulted from the match should be:
["word","word","two words","word"]
Could someone help or give me some insight on how would i go about doing this?
Thank you
Edit: what I've tried and succeed is doing it in two parts:
match(/[^(,)]+/g)
and using map to remove all the spaces from the resulting array:
map(value => value.trim());
But would like to do it only through regular expression and have no idea how to do it.
\w[\w ]*?(?:(?=\s*,)|$)
Explanation:
\w[\w ]*?
Matches word characters with 0 or more spaces in between, but never at the start. (lazy)
(?:(?=\s*,)|$)
This non-capturing group looks ahead for spaces followed by ,
, or the end of string.
Try it here.
You can just split on comma surrounded by optional spaces on either side:
var str = "word , , word , two words, word";
var arr = str.split(/(?:\s*,\s*)+/);
console.log(arr);
//=> ["word", "word", "two words", "word"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With