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

185
Vistas
Why this regex returns character instead of newline

I want to insert something just before "test", I use this regex and expected that it would return newline but it returns "h" so if I insert with replace method I would not actually insert before "test" as I want : where's the mistake?

https://jsfiddle.net/y4qh629a/

  const test = `
  blah blah
  test blah blah`;

  const regex = /[^"]\s*(?=test)/;
  const match = test.match(regex);
  alert(match)
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The negated character class [^"] consumes a single character other than an " char, in this example that is the h char.

If you want to add something before the match, you can use replace instead or concat the value returned by match (note that match returns an array, and that const test can not be overwritten)

In this case, you can capture the full match using. In the replacement use the full match using $&.

Note that there should be at least a single character other than " present, which can also be a whitspace char.

const test = `
  blah blah
  test blah blah`;


console.log(test.replace(/[^"]\s*(?=test)/, "$&[replacement]"));

If you also want to match test at the start of the string:

const test = `test here
  blah blah
  test blah blah`;

console.log(test.replace(/(?:^|[^"])\s*(?=test)/g, "$&[replacement]"));

about 4 years ago · Juan Pablo Isaza Denunciar

0

[^"] matches a single character.

Maybe you want to match unlimited times? Just add + a.e. [^"]+

const regex = /[^"]+\s*(?=test)/;

Fiddle

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use a negative lookbehind instead:

(?!<=")\s*(?=test)

const test = `
      blah blah
      test blah blah`;

const regex = /(?!<=")\s*(?=test)/;
const match = test.match(regex);
console.log(match)

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