简体   繁体   中英

JavaScript: How to split string into array based on a curly-braces-pattern?

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:)

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM