繁体   English   中英

如何通过正则表达式将带有标签的javascript字符串包装在另一个标签中?

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

我有带链接的字符串

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

我需要在<span>元素中将链接内的文本包装起来

喜欢

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

那么我需要什么正则表达式? 附言。 我需要通过 nodejs 将此字符串作为 html 邮件的一部分从 mongodb 发送,而不是用于操作 DOM

将 DOMParser 与 node.js 一起使用是最安全的,因为提到了“第四只鸟”: Trying to use the DOMParser with node js

您可以使用正则表达式,它可能无法涵盖所有极端情况。 这里有两个选项:

 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);

输出:

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>

regex1的解释:

  • (<a [^>]*>) -- 捕获组1:锚标签
  • (.*?) -- 捕获组 2:非贪婪扫描
  • (<\/a>) -- 捕获组3:锚点结束标签
  • 在替换部分使用捕获的组$1$2$3

regex2的解释:

  • 类似于 regex1,但使用正向后视而不是捕获组 1,并使用正向前视而不是捕获组 2(并非所有 JavaScript 引擎都支持)

使用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>

我们也可以通过简单地使用String.replace()方法来实现这一要求。

现场演示

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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