2

i need to split a string by semicolon, colon, comma, cr, lf, clfr and whitespace. How can i do that?

2 Answers 2

7

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(/;|,| /);
Sign up to request clarification or add additional context in comments.

4 Comments

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?
it would help if you would post a sample string to work with. :)
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.
it's easy to just remove the empty strings from the resulting array with filter splitted.filter(c => c)
0

I would recommend /[,.;/ ]/ regex. It will split with all provided chars between []

"55,22.222;55 555".split(/[,.;/ ]/)

"15/01/2020".split(/[,.;/ ]/)

(Remove last empty space if you don't want to split by space => /[,.;/]/ )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.