Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

I suggest that you standardized your string before split to array

Replace all ` to " and so

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda