Home > Enterprise >  javascript split string on curly brackets
javascript split string on curly brackets

Time:12-06

I'm implementing a search (autocomplete) solution where words inside these curly brackets { } are the one that you already typed while the rest is autosuggested

with the search query of "big boy jeans skate" and "fast skateboard wheel company lo" I get this string back from the search-api:

"{big} {boy} {jeans} polar {skate} co. teal"

"{fast skateboard wheel company} {lo}ngboardhjul lys beige"

i need to find a regex that splits this into:

['{big}', '{boy}', '{jeans}', 'polar', '{skate}', 'co.', 'teal']

['{fast skateboard wheel company}', '{lo}ngboardhjul', 'lys', 'beige']

what I've tried so far is to split on this:

const regex = / (?=[^\}[\s] (?:\{[^\}[]*])?(?!\S))/g;

but it didn't give me the results i wanted, anyone who is a regex mastermind that can help me?

CodePudding user response:

I would use a regex find all approach with match():

var input = "{big} {bo}ys {jeans} polar {skate} co. teal";
var parts = input.match(/\{.*?\}\S*|\S /g);
console.log(parts);

  • Related