i need to split a string by semicolon, colon, comma, cr, lf, clfr and whitespace. How can i do that?
2 Answers
You can give the split function a regex to split it by.
A simple one looks like this.
const text = "a,c;d e";
const splitted = text.split(/;|,| /);
4 Comments
NKara
Thanks, that helps a lot but i have a problem: When I split a string with a linebreak like "a b" the array I get is ['a', '', 'b'] but it should be ['a', 'b']. How can I fix this?
toskv
it would help if you would post a sample string to work with. :)
toskv
for example:
"a,c;d e\nx" splits nicely with /;|,| |\n/, however "a,c;d e\n x" generates an empty string when split because there are 2 separators next to each other in the original string.toskv
it's easy to just remove the empty strings from the resulting array with filter
splitted.filter(c => c)