Usr
Usr

Reputation: 2838

Typescript string.split with regex with char followed by space and space only

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?

Upvotes: 2

Views: 2472

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626961

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+/));

Upvotes: 2

Related Questions