简体   繁体   English

如何用HTML标签替换包含字符串的文本?

[英]How to replace text containing string with a HTML tag?

I am trying to work out how to replace any instance of text on page matching a certain phrase with a HTML tag - the contents should remain the same. 我正在尝试找出如何用HTML标记替换与某个短语匹配的页面上文本的任何实例-内容应保持不变。

bold("Hello")

The code above should be replaced with: 上面的代码应替换为:

<b>Hello</b>

Here is the code that I am currently using: 这是我当前正在使用的代码:

node.data = node.data.replace('bold("','<b>');
node.data = node.data.replace('")','</b>');

The problem with this is that rather than creating a <b> tag, it converts the < and > into their HTML entities - &lt; 问题在于,它不是创建<b>标记,而是将<>转换为它们的HTML实体- &lt; &gt; &gt; .

Also, it seems unpractical to replace all instances of ") with </b> . 另外,用</b>替换所有")实例似乎不切实际。

What would be the best way to achieve this. 什么是实现这一目标的最佳方法。

I would appreciate any help with this, thank you! 感谢您的帮助,谢谢!

I assume you don't literally mean all text on a page, but rather all text inside of a given element. 我假设您不是从字面上看是指页面上的所有文本,而是指给定元素内的所有文本。 DucFilans is right on the money with regex, I'll slightly modify his answer to provide a complete working solution: DucFilans使用正则表达式是对的,我将略微修改他的答案以提供完整的工作解决方案:

 var parserRules = [ { pattern: /bold\\("(.*?)"\\)/g, replacement: '<b>$1</b>' }, { pattern: /italics\\("(.*?)"\\)/g, replacement: '<i>$1</i>' } ]; document.querySelectorAll('.parse').forEach(function(tag) { var inner = tag.innerHTML; parserRules.forEach(function(rule) { inner = inner.replace(rule.pattern, rule.replacement) }); tag.innerHTML = inner; }); 
 <div class='parse'> <div>bold("Hello") world <p> Rose italics("pink") slow bold("!") </p> </div> <div>bold("astiago") cheeeeeeese!</div> </div> 

You can define the regex patterns and replacement rules in the parserRules array, and then any element marked with the 'parse' class will be parsed. 您可以在parserRules数组中定义正则表达式模式和替换规则,然后将解析所有标记有'parse'类的元素。 One warning is that this will replace all of the subelements, so if you are relying on listeners attached to subelements or something similar you'll need to take care of that as well. 一个警告是,这将替换所有子元素,因此,如果您依赖于附加到子元素或类似元素的侦听器,则也需要注意这一点。

Regex helps in your concern of replacement. 正则表达式可帮助您解决更换问题。

 var str = 'bold("Hello")'; var regex = /bold\\("(.*?)"\\)/; str = str.replace(regex, "<b>$1</b>"); console.log(str); 

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

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