2

Using JavaScript, Is there a way to split the string to an array with two separators: ':' and ','

For var str = "21:223, 310:320";

would like the Result to be: [21, 223, 310, 320];

Thanks!

2 Answers 2

3

You could use a regular expression which looks for a : or for a comma with an optional space ,.

console.log("21:223, 310:320,42".split(/:|, */));

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

2 Comments

Hi the above works for comma with space after that. Do you know how can I add separator for comma without a space after that ?
Thanks @Nina Scholz!
1

You can use match if your expression is like this "21:223, 310:320"

var str = "21 :  223 , 310 :  320 ";
//---------^^----^^^---^^^----^^^--
// group of digits(represented by ^) will be matched
console.log(str.match(/(\d+)/g));
// will return ["21", "223", "310", "320"]

1 Comment

Thanks @suraj.tripathi!

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.