Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
How can I split a string via first level square brackets?

I have a string like this:

key[type=order][0].item[id={getVal(obj[type=item][0].id)}]

and I want to split this string as like:

 [
     ['key', '[type=order]', '[0]'],
     ['item', '[id={getVal(obj[type=item][0].id)}]']
 ]

Firstly I split string via first level dot:

const str = 'key[type=order][0].item[id={getVal(obj[type=item][0].id)}]';
const arr = str.split(/\.(?![^[]*])/).filter(Boolean);

This generated array like this:

['key[type=order][0]', 'item[id={getVal(obj[type=item][0].id)}]']

And after that I want to split all array item via first level square bracket with:

arr.map(item => item.split(/(\[.+?\])/).filter(Boolean))

This generated array:

[
    ['key', '[type=order]', '[0]'],
    ['item', '[id={getVal(obj[type=item]', '[0]', '.id)}]']
]

I want to split items only first level square brackets not nested. How can I do this with regex in javascript?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

this should do it on your final split

arr.map(item => item.split(/(\[[^\]]+\(.*\).*\])|(\[.+?\])/).filter(Boolean))

Which generates the array:

[
    ['key', '[type=order]', '[0]'],
    ['item', '[id={getVal(obj[type=item][0].id)}]']
]

The regex is /(\[[^\]]+\(.*\).*\])|(\[.+?\])/ and the first part of that looks for any square brackets with parentheses inside, and discounts any square brackets within those. After the | (or) your original regex runs!

Update

arr.map(item => item.split(/(\[[^\]]+\([^\)]*\)[^\]]*\])|(\[.+?\])/).filter(Boolean))
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda