jQuery在不在P,DIV,SPAN,TD之外的html标签内查找/替换html文本

问题描述:

我有一个html文本片段,它是我需要运行查找/替换的页面DOM的一部分,我需要一些帮助来找出创建查找/替换功能的最佳方法。

I have an html text fragment that's part of the page's DOM that I need to run a find/replace on and I need some help figuring out the best way to create the find/replace function.

例如,我想获取id =content的dom对象的内容,并使用目标搜索短语运行查找替换。

For example, I would like to take the contents of the dom object whose id="content" and run a find replace using a target search phrase.

我需要用< b> The Phrase< / b>替换它在内容中找到的短语的每个实例的功能,前提是该短语确实不会出现在div,p,span或td标签以外的任何标签内,并返回替换的xhtml文本。

I need the function to replace each instance of the phrase it finds in the content with "<b>The Phrase</b>", providing that the phrase does not appear inside of any tag other than a div, p, span or td tag, and return the replaced xhtml text.

我可以使用jQuery dom遍历和一些替换方法?

Can I do this with jQuery dom traversal along with some replace method?

这就是我以前寻找搜索字符串的方法。 RegEx检查不属于HTML标记的文本。在替换函数 $& 中引用匹配的字符串。

This is what I used to look for a search string. The RegEx checks for text that does not belong to an HTML tag. In the replace function $& references the string that was matched.

var rx = new RegExp('(?![^<]+>)' + searchString, 'gi');

$(this).html(function (i, html) {
   return html.replace(rx, '<b>$&</b>')
});

至于不属于任何其他HTML标签,您必须提供一个示例。这就是它可能变得棘手的地方。

As for not belonging to any other HTML tags, you'll have to provide an example. That's where it could get tricky.