Reputation: 38228
I'm still sucking at regex. I tried in chrome dev tools:
regex = /\s|[(\;)]/;
test = "test test-test-test test;"
test.split(regex);
It didn't keep ";"
["test", "test-test-test", "test", ""]
whereas I wanted to get
["test", "test-test-test", "test", ";"]
Upvotes: 0
Views: 36
Reputation: 522636
Consider splitting on the following slightly updated regex:
\s|(?=;)
This splits on a whitespace character or on a zero-width positive lookahead which asserts semicolon. The lookahead does not consume anything.
test = "test test-test-test test;"
var out = test.split(/\s|(?=;)/);
console.log(out);
Upvotes: 1
Reputation: 371148
Your [(\;)]
will match either a (
, a ;
, or a )
. If you wanted that to be a capture group, move it outside the character set, and filter out empty/undefined results to account for when the capture group is not matched. Since all you want to match is ;
, there's no need for a character set anymore either:
regex = /\s|(;)/;
test = "test test-test-test test;"
console.log(test.split(regex).filter(Boolean));
Upvotes: 2