简体   繁体   English

JavaScript用方括号和数字分隔

[英]Javascript split by square brackets and numbers

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. 但无法正确拆分。

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数字。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM