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

184
Vistas
regex to match all elements inside string

i want to get all strings between brackets []. i tried regex match methode and it's not working

i only get the first element changed

here is my code

tags = "[r,a,9]@[r,a,8].com".match(/([(?:[??[^[]*?]))/);
for (let index = 0; index < tagNumber; index++) {
  console.log(tags[index]);
  fromName = "[r,a,9]@[r,a,8].com".replace(tags[index], "haha");
}

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

/\[.+?\]/g

/ denotes the start of the pattern

\[ matches the [ character

.+? matches any character, 1 or more times, lazily

\] matches the ] character

/g denotes the end of the pattern and to find ALL matches

const input = "[r,a,9]@[r,a,8].com"
const pattern = /\[.+?\]/g

const tags = Array.from(input.match(pattern))
console.log(tags)

const fromName = input.replace(pattern, "haha")
console.log(fromName)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to escape [ and ] to match them literally. There's no need for the capture group around everything.

Add the g modifier to match all the occurrences in the string.

tags = "[r,a,9]@[r,a,8].com".match(/\[[^[]*?\]/g);
let tagNumber = tags.length;
for (let index = 0; index < tagNumber; index++) {
  console.log(tags[index]);
  fromName = "[r,a,9]@[r,a,8].com".replace(tags[index], "haha");
  console.log(fromName)
}

You can use a regular expression in replace() to replace all the matches at once.

fromName = "[r,a,9]@[r,a,8].com".replace(/\[[^[]*?\]/g, "haha");
console.log(fromName)

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