Home > database >  Remove <a href > tag if it has specific format using regex in javascript
Remove <a href > tag if it has specific format using regex in javascript

Time:10-04

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)

CodePudding user response:

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)

CodePudding user response:

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

  • Related