3

I have a string of this type:

string = "test1; test2, test3 test4;test5"

I need to split it and get an array with the 5 words. I do this:

let arrayTo:string[] = string.split(/;|,|, |; | /);

but what I get is an array of 7 elements, two of them are empty strings:

["test1","","test2","","test3","test4","test5"]

I would like to consider , and ; followed by whitespace as one entity and split on them, but with this regex it splits also on the whitespace that follows these characters. But I need also to split by whitespace alone (in this case, it correctly splits test3 and test4 in two entities).
What is the correct way to do this?

2
  • You split by ; (semi-column) first, instead of ; (semi-column space). Commented Oct 2, 2019 at 14:13
  • 2
    Try split(/[;,]\s*|\s+/) Commented Oct 2, 2019 at 14:13

1 Answer 1

3

You may use

string.split(/[;,]\s*|\s+/)

The regex matches

  • [;,]\s* - a ; or , and then 0+ whitespaces
  • | - or
  • \s+ - 1+ whitespaces.

JS demo:

string = "test1; test2, test3 test4;test5";
console.log(string.split(/[;,]\s*|\s+/));

Sign up to request clarification or add additional context in comments.

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.