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

109
Vistas
Remove <a href > tag if it has specific format using regex in javascript

I have the an anchor tag in this format (username as link text) <a href="#">@rey</a>.

I want to remove a tag only if <a> tag contains the username format (@username).

Currently I have the following code for the task but it is not working as expected

let message= "Hello <a href="#">@rey</a> how are you doing ?"
const regex = /\B<a href='#'>@(\S+)<\/a>/g
const subst = `@$1`
message = message.replace(regex, subst)
console.log(message)
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Assuming the tag could be anything, use this regex:

<(\w+)\b[^>]+>@(?<username>\w+)<\/\1>

if tag is fixed (i.e. <a>)

<a[^>]*>@(?<username>\w+)<\/a>

The replacment code:

let message= 'Hello <a href="#">@rey</a> how are you doing ?'
const regex = /<(\w+)\b[^>]+>@(?<username>\w+)<\/\1>/g;
message = message.replace(regex, `$<username>`)
console.log(message)

"Hello rey how are you doing ?"

Check the result here

about 4 years ago · Juan Pablo Isaza Denunciar

0

Quotation issue in the let instruction. The following should work :

let message= "Hello <a href='#'>@rey</a> how are you doing ?"
const regex = /\B<a href='#'>@(\S+)<\/a>/g
const subst = `@$1`
message = message.replace(regex, subst)
console.log(message)

or even

let message= 'Hello <a href="#">@rey</a> how are you doing ?'
const regex = /\B<a href="#">@(\S+)<\/a>/g
const subst = `@$1`
message = message.replace(regex, subst)
console.log(message)

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