0

I have string with link

<a href="https://twitter.com/" target="_blank" rel="noopener noreferrer">Twitter/</a>

and I need to wrap a text inside link in a <span> element

like :

<a href="https://twitter.com/" target="_blank" rel="noopener noreferrer"><span style="color: white">Twitter</span>/</a>

so what regex i need ? ps. i need to send this string as part of html mail letter from mongodb via nodejs, not for manipulate DOM

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
Mithra
  • 39
  • 5

3 Answers3

1

It's safest to use a DOMParser with node.js as "The fourth bird" mentioned: Trying to use the DOMParser with node js

You can use a regex, which might not cover all corner cases. Here are two options:

const input = '<a href="https://twitter.com/" target="_blank" rel="noopener noreferrer">Twitter/</a>';

let regex1 = /(<a [^>]*>)(.*?)(<\/a>)/gi;
let result1 = input.replace(regex1, '$1<span style="color: white">$2</span>$3');
console.log('result1:', result1);

let regex2 = /(?<=<a [^>]*>)(.*?)(?=<\/a>)/gi;
let result2 = input.replace(regex2, '<span style="color: white">$1</span>');
console.log('result2:', result2);

Output:

result1: <a href="https://twitter.com/" target="_blank" rel="noopener noreferrer"><span style="color: white">Twitter/</span></a>
result2: <a href="https://twitter.com/" target="_blank" rel="noopener noreferrer"><span style="color: white">Twitter/</span></a>

Explanation of regex1:

  • (<a [^>]*>) -- capture group 1: anchor tag
  • (.*?) -- capture group 2: non-greedy scan
  • (<\/a>) -- capture group 3: anchor end tag
  • in replacement part use captured groups $1, $2, $3

Explanation of regex2:

  • similar to regex1, but using a positive lookbehind instead of capture group 1, and a positive lookahead instead of capture group 2 (this is not supported by all JavaScript engines)
Peter Thoeny
  • 7,379
  • 1
  • 10
  • 20
0

Using jsdom

var anchor = document.querySelector("a");
var anchorText = anchor.textContent;

anchor.innerText = "";
var span = document.createElement("span");
var spanText = document.createTextNode(anchorText);
span.appendChild(spanText)
anchor.appendChild(span);

console.log(anchor.innerHTML);
<a href="https://twitter.com/" target="_blank" rel="noopener noreferrer">Twitter/</a>
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
0

We can also achieve this requirement by simply using String.replace() method.

Live Demo :

var anchor = document.querySelector("a");
var anchorText = anchor.textContent;

anchor.innerHTML = anchorText.replace(anchorText, `<span style="color: red">${anchorText}</span>`)
<a href="https://twitter.com/" target="_blank" rel="noopener noreferrer">Twitter/</a>
Debug Diva
  • 26,058
  • 13
  • 70
  • 123