0

I want to split a string similar to this:

"2*{some_string}*8*{some_other_string}"

Into an array, keeping the curly braces intact:

["2*","{some_string}","*8*","{some_other_string}"]

I'm hitting a wall and always end up remove the curly braces. Any clues out there?

I've been working with something like this:

var found = [],          // an array to collect the strings that are found
    rxp = /{([^}]+)}/g,
    str = "a {string} with {curly} braces",
    curMatch;

while( curMatch = rxp.exec( str ) ) {
    found.push( curMatch[1] );
}

console.log( found );    // ["string", "curly"]

Thanks :)

2
  • 1
    what have you tried so far ? please post the code Commented Apr 15, 2020 at 5:32
  • Updated my post above :) Commented Apr 15, 2020 at 6:04

1 Answer 1

3

Don't really need replace. You can keep the {} when you split it by using regex, but it will create empty string, so you will need to use filter to remove empty string in the array after splitting.

console.log("2*{some_string}*8*{some_other_string}".split(/({.*?})/).filter(s => !!s))

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.