Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!