简体   繁体   中英

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?

I tried this:

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

but it's not splitting correctly.

Use this regex: /\\]|\\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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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