2

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", ""]

1
  • 4
    .split(/{.*?}/). Commented Feb 21, 2018 at 5:05

1 Answer 1

3

.* 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 ", ""]

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

Comments

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.