简体   繁体   中英

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

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

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)

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM