I have some text. And I have a function that receives a word or phrase and I have to return the same text but with a span with a class around this keyword or phrase.
Example:
If I have this
text = <a href="/redirect?uri=https%3A%2F%2Fwww.website.com&context=post" target="_blank" rel="noopener noreferrer">https://www.website.com</a>
I want
text = <a href="/redirect?uri=https%3A%2F%2Fwww.website.com&context=post" target="_blank" rel="noopener noreferrer">https://www.<span class="bold">website</span>.com</a>
but what I'm getting is
text = <a href="/redirect?uri=https%3A%2F%2Fwww.<span class="bold"> website </span>.com&context=post" target="_blank" rel="noopener noreferrer">https://www.<span class="bold"> website </span>.com</a>
What I'm doing is
...
const escapedPhrases = ["\\bwebsite\\b"]
const regex = new RegExp(`(${escapedPhrases.join('|')})`, 'gi');
text = text.replace(
regex,
'<span class="bold"> $1 </span>'
);
How can I improve my regex?
Also I have tried to "clean" the text after the replacement of <span class="bold"> $1 </span>
to try of remove it if it's inside the href but with no success.
UPDATE for clarification:
I have this text:
text = `Follow me on
<a href="/redirect?uri=https%3A%2F%2Fwww.twitter.com&context=post" target="_blank" rel="noopener noreferrer">https://www.twitter.com</a>
Thanks!`
Example 1:
I want to highlight the word twitter
:
For this I want to add a span with class bold
for example around twitter:
text = `Follow me on
<a href="/redirect?uri=https%3A%2F%2Fwww.twitter.com&context=post" target="_blank" rel="noopener noreferrer">https://www.<span class="bold">twitter</span>.com</a>
Thanks!`
Example 2:
I want to highlight the word twitter.com
:
For this I want to add a span with class bold
for example around twitter.com
:
text = `Follow me on
<a href="/redirect?uri=https%3A%2F%2Fwww.twitter.com&context=post" target="_blank" rel="noopener noreferrer">https://www.<span class="bold">twitter.com</span></a>
Thanks!`
Example 3:
I want to highlight the word https://twitter.com/
:
For this I want to add a span with class bold
for example around https://twitter.com/
:
text = `Follow me on
<a href="/redirect?uri=https%3A%2F%2Fwww.twitter.com&context=post" target="_blank" rel="noopener noreferrer"><span class="bold">https://www.twitter.com</span></a>
Thanks!`
Example 4:
I have this text and want to highlight twitter
:
text = `Follow me on
<a href="/redirect?uri=https%3A%2F%2Fwww.twitter.com&context=post" target="_blank" rel="noopener noreferrer">https://www.twitter.com</a>
Thanks for follow my twitter!`
Then I have to return
text = `Follow me on
<a href="/redirect?uri=https%3A%2F%2Fwww.twitter.com&context=post" target="_blank" rel="noopener noreferrer">https://www.<span class="bold">twitter</span>.com</a>
Thanks for follow my <span class="bold">twitter</span>!`