11

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

2 Answers 2

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

See this demo.

Sign up to request clarification or add additional context in comments.

2 Comments

Please provide an explanation, without one this answer isn't especially helpful.
I think the code says it all. This is exactly what I was looking for. We can also use "(text1)(text2)(text3)".split(/[()]+/).filter(String); to get rid of that nasty little empty string.
2

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)

4 Comments

this answer is the most sensible for behaviour OP wants, (not a simple string split) but will fail for e.g. "(text(1)(text(2)". You can make this match the opening parentheses, too, then map them out; .match(/\([^)]+/g).map(function (e) {return e.slice(1);});
@PaulS sure, but that seems rather invalid. and things with proper nesting can't be matched anyway. I mean, why support (text(1)(text(2) but not (1)text)(2)text) or (te(1)xt)(te(2)xt)?
True. I was trying to think how to do all of them without needing a loop, but a second ( defiantly would not be the end of the section, whereas a second ) could be. It isn't the biggest issue in the world though.
@PaulS. allowing arbitrary nesting is the biggest issue in the world, if you want to solve it with a JavaScript regex ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.