11

Tengo el siguiente código:

text = 'check this regex<placeholder>, it will do what you want';
result = text.replace('<placeholder>', ' `^sql$`');

console.log(result);

Como pueden ver, el resultado es

check this regex `^sqlcheck this regex, it will do what you want

Cuando esperaría que sea

check this regex `^sql$`, it will do what you want

Por qué pasa esto? y... cómo puedo arreglarlo?

0

1 respuesta 1

22

La función replace tiene un comportamiento interesante respecto al segundo parámetro: (las negritas son mías).

The replacement string can include the following special replacement patterns:

Pattern Inserts

  • $$ Inserts a "$".
  • $& Inserts the matched substring.
  • $` Inserts the portion of the string that precedes the matched substring.
  • $' Inserts the portion of the string that follows the matched substring.
  • $n Where n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. Note that this is 1-indexed.

Traducción aproximada:

El string de reemplazo puede incluir los siguientes patrones de reemplazo:

  • $$ inserta un "$".
  • $& Inserta el substring que coincide con la búsqueda.
  • $` Inserta la porción del string que precede al substring que coincide con la búsqueda.
  • $' Inserta la porción del string que sigue al substring que coincide con la búsqueda.
  • $n Donde n es un número entero positivo y menor a 100, inserta la n-ésima sub-coincidencia entre paréntesis (grupo de captura), asumiendo que el patrón (primer parámetro) es una expresión regular.

Es decir, en este caso se añade ^sql y tras esto se añade todo el string que precede al match. Se puede solucionar duplicando el carácter $:

const text = 'check this regex<placeholder>, it will do what you want';
const result = text.replace('<placeholder>', ' `^sql$$`');
//                                                  ^^
console.log(result);

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.