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

123
Vistas
¿Cómo reutilizar el valor coincidente de expresiones regulares en la función JS replace () en la función misma?

Digamos que tengo una cadena, quiero obtener una coincidencia en alguna cadena. Para encontrarlo, uso expresiones regulares y luego lo reemplazo. Sin embargo, ¿cómo lo reemplazaría con el partido en sí pero editado?

Tengo dificultades para usar match() y matchAll() porque el texto de entrada no es necesariamente una cadena y las salidas de las funciones de coincidencia no tienen ningún sentido en el contexto en el que lo estoy usando. Vuelven como RegExpStringIterator(s).

Objetivo:

Intentando hacer una extensión de Google que edite el contenido de la página.

Ex.

 regex = /123/g let text = "XYZ string is some string is a string, but 123 is what I want to change." let edit = text.replace(regex, numGen(***not sure what to pass here***)) console.log(edit) function numGen(match) { //Here I want to get the match and add the string "4" to it } """ Expected outcome of "console.log(edit)": XYZ string is some string is a string, but ***1234*** is what I want to change. """
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Según su ejemplo, si solo necesita agregar cadenas (por ejemplo, texto) al resultado coincidente, simplemente puede usar replace() :

 const regex = /123/g; const text = "XYZ string is some string is a string, but 123 is what I want to change."; const edit = text.replace(regex, '***$&***'); // $& means the whole matched string // result: XYZ string is some string is a string, but ***123*** is what I want to change.

Si necesita ejecutar algún código para cambiar el resultado coincidente, puede usar una función de replacerFunction :

 const regex = /123/g; const text = "XYZ string is some string is a string, but 123 is what I want to change."; const edit = text.replace(regex, function(m) { // m here means the whole matched string // for example, let's double the number return m * 2; // resulat: XYZ string is some string is a string, but 246 is what I want to change. });

Igual que arriba pero usando la función de flecha:

 const regex = /123/g; const text = "XYZ string is some string is a string, but 123 is what I want to change."; const edit = text.replace(regex, m => { // m here means the whole matched string // for example, let's double the number return m * 2; // result: XYZ string is some string is a string, but 246 is what I want to change. });

Nota: Para una sola operación, lo anterior también se puede escribir como:

 const edit = text.replace(regex, m => m * 2);
about 4 years ago · Juan Pablo Isaza Denunciar

0

¿Quieres decir esto? Comprobar comentarios en línea

UPD con función externa de llamada en el partido

 // External function to call with each match const numGen = match => { // Here you get the match as argument from replace function // Then add the string "4" to it match += "4"; // Then return final result back to replace return match; } // Replace method part const regex = /string/g; let counter = 0; let text = "XYZ string is some string is a string."; // Just set your external function as replace parameter. // Matched string will be passed to it as arguments let edit = text.replace(regex, numGen); // Result console.log(edit);

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