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

213
Vistas
Regex to split a string into args without breaking the quoted text

I want to take all words from a string and convert them into an array, but i don't want to break sentences that are enclosed in quotes

My code:

const content = 'this is a simple text that i "need to split into" arguments'
const args = content.split(/ +/g)
console.log(args)

// Result: ['this', 'is', 'a', 'simple', 'text', 'that', 'i', '"need', 'to', 'split', 'into"', 'arguments']

What do I need as a result:

// Result: ['this', 'is', 'a', 'simple', 'text', 'that', 'i', 'need to split into', 'arguments']
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

One simple approach would be to use string match() along with the regex pattern ".*?"|\w+. This pattern will eagerly first try to find a next doubly-quoted term. That failing, it will search for a single word. This approach avoids the possibility of consuming words which appear inside double quotes.

var content = 'this is a simple text that i "need to split into" arguments';
var matches = content.match(/".*?"|\w+/g);
for (var i=0; i < matches.length; ++i) {
    matches[i] = matches[i].replace(/^"(.*)"$/, "$1");
}
console.log(matches);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Assuming there are no escaped quotes, and the quotes are correctly paired up.

const content = 'this is a simple text that i "need to split into" arguments'
args = content.split(/\s(?=(?:[^"]*"[^"]*")*[^"]*$)/g);
console.log(args);

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