user4324324
user4324324

Reputation: 559

Split using two delimiters

How to split using two delimiters. Below is my code where I am splitting the string using (). How to split both using () and {( in the below string.

var str = 'abc xyz() ab{( }) pp '
var res = str.split("()");
console.log(res); //[ 'abc xyz', ' ab{( }) pp ' ]

I have tried something like this, which does not split properly

res = str.split(/[\})\()/]/

I am expecting something like below

[ 'abc xyz', ' ab', '}) pp ' ]

If str = 'abc xyz() ab{( }) pp bb yy{( kk llop', I want the output to be [ 'abc xyz', ' ab', '}) pp bb yy{( kk llop' ]. The split must happen only on the first occurrence.

Upvotes: 0

Views: 83

Answers (2)

epascarello
epascarello

Reputation: 207501

Use Or |

'abc xyz() ab{( }) pp '.split(/\(\)|\{\(/)

Upvotes: 1

Matt Burland
Matt Burland

Reputation: 45135

var str = 'abc xyz() ab{( }) pp '

var result = str.split(/(?:\(\)|\{\()/);

alert(JSON.stringify(result));

Something like:

str.split(/(?:\(\)|\{\()/)

You use | to specify either match () OR {(. The ?: makes it non-capturing.

Upvotes: 0

Related Questions