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

157
Visualizações
How can I split a string input in Javascript by each spacebar, but not elements inside double "quotes", single 'quotes' or backticks

I'm trying to get an array of arguments from a string by doing the following

const str = `argument "second argument" 'third argument' \`fourth argument\``;

str.split(/\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)/g);

The expected output:

['argument', '"second argument"', "'third argument'", '`fourth argument`']

But this comes out:

['argument', '`', '"second argument"', '`', "'third argument'", '`', '`fourth argument`']

How can I get back an array of just 4 elements?

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

0

After getting an array then you can use filter to filter out the unwanted string

const str = `argument "second argument" 'third argument' \`fourth argument\``;

const result = str
  .split(/\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)/g)
  .filter((s) => /[a-z]/.test(s));

console.log(result);

You can also achieve the same result using string manipulation

const str = `argument "second argument" 'third argument' \`fourth argument\``;

const replacerFn = (match) => match.split(" ").join("_");
const result = str
  .replace(/".*?"|'.*?'|`.*?`/g, replacerFn)
  .split(" ")
  .map((s) => s.split("_").join(" "));

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

I suggest that you standardized your string before split to array

Replace all ` to " and so

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