Home > Net >  how to wrap javascript string with tag in another tag by regex?
how to wrap javascript string with tag in another tag by regex?

Time:12-14

i have string with link

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

and i need to wrap text in link in <span> 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

CodePudding user response:

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)

CodePudding user response:

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>

  • Related