zaitsman
zaitsman

Reputation: 9499

Javascript regex - split string by string between two characters

Say i have a string like so

Shoes {cakes} marry me {fiona:banana|cheese} and then {i want}

I want to get an array like so

["Shoes", " marry me ", " and then "]

or even

["Shoes", " marry me ", " and then ", ""]

I know that if i have a single char, e.g.

Shoes {a} marry me {b} and then {c}

I can do "Shoes {a} marry me {b} and then {c}".split(/\{.\}/) to get my result.

I tried

"Shoes {cakes} marry me {fiona:banana|cheese} and then {i want}".split(/\{(.*)\}/)

But my result looks like

["Shoes ", "cakes} marry me {fiona:banana|cheese} and then {i want", ""]

Upvotes: 2

Views: 50

Answers (1)

Amadan
Amadan

Reputation: 198324

.* will take as much as it can ("greedy repetition"). .*? will take as little as possible:

let haystack = "Shoes {cakes} marry me {fiona:banana|cheese} and then {i want}";
let needle = /{.*?}/;
console.log(haystack.split(needle));
// => ["Shoes ", " marry me ", " and then ", ""]

Upvotes: 3

Related Questions