Javascript由方括号和数字分隔

时间:2022-01-12 21:42:36

How can I use the js split function to split a string by a closing square bracket character (]) as well as numbers, '1' '2' '3' etc?

如何使用js split函数通过结束方括号字符(])以及数字“1”,“2”和“3”等分割字符串?

I tried this:

我试过这个:

text.split(/[\\[123456789]/);

but it's not splitting correctly.

但它没有正确分裂。

2 个解决方案

#1


2  

Use this regex: /\]|\d+/

使用这个正则表达式:/ \] | \ d + /

Example below:

string = 'example] with 0.. 12.. 3.. some] numbers 1232';
document.body.innerHTML = string.split(/\]|\d+/).join`<br>`;

Explaining:

\]      # literal ']' character
|       # OR
\d+     # any number

If you want to split by each digit instead of the whole number just remove the plus + sign. The + plus sign is there just to match \d digits in group.

如果要按每个数字而不是整数进行拆分,只需删除加号+。 +加号只是匹配组中的\ d数字。

#2


0  

var str = 'all1the2words3you]need';
console.log(str.split(/[\d\]]/)); //["all", "the", "words", "you", "need"]

#1


2  

Use this regex: /\]|\d+/

使用这个正则表达式:/ \] | \ d + /

Example below:

string = 'example] with 0.. 12.. 3.. some] numbers 1232';
document.body.innerHTML = string.split(/\]|\d+/).join`<br>`;

Explaining:

\]      # literal ']' character
|       # OR
\d+     # any number

If you want to split by each digit instead of the whole number just remove the plus + sign. The + plus sign is there just to match \d digits in group.

如果要按每个数字而不是整数进行拆分,只需删除加号+。 +加号只是匹配组中的\ d数字。

#2


0  

var str = 'all1the2words3you]need';
console.log(str.split(/[\d\]]/)); //["all", "the", "words", "you", "need"]