regex split string with two separators

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!

Answer1:

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

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

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


Answer2:

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

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

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"]


人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:regex split string with two separators