简体   繁体   中英

How to split string between two separators in javascript?

I know how to split using, multiple separators but I have no idea how to split a string into an array between two characters. So:

var myArray = "(text1)(text2)(text3)".split(???)
//=> myArray[0] = "text1", myArray[1] = "text2", myArray[2] = "text3"

What should I enter in the "???"? Or is there a different approach I should use?

Making ")(" a separator won't work as I want to split the array with a variety of separators such as ">" making it very unpractical to list every possible combination of separators

.split(/[()]+/).filter(function(e) { return e; });

这个演示

Using split between specific characters without losing any characters is not possible with JavaScript, because you would need a lookbehind for that (which is not supported). But since you seem to want the texts inside the parentheses, instead of splitting you could just match the longest-possible string not containing parentheses:

myArray = "(text1)(text2)(text3)".match(/[^()]+/g)

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