正则表达式在页面上找到包含内部标签的单词 [英] Regex to find word on page including inside tags

查看:170
本文介绍了正则表达式在页面上找到包含内部标签的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢 Chetan Sastry 我有这个正则表达式代码来解析我的页面,列出一个单词,并添加

  var wordList = [jQuery UI,jQuery,is]; 
var regExp = new RegExp(\\b+ wordList.join(\\b | \\\b)+\\b,g);
var $ elem = $(#divWithText);
$ elem.html($ elem.html()。replace(regExp,$&& trade;));

这个正则表达式几乎是我需要的。
但是,一个链接看起来像:

 < a href =/ 0 / products / jQuery > jQuery和LT; / A> 

它最终将TM添加到href中的jQuery,而不是标签之间的jQuery。



有人可以帮忙吗?



我要查找的单词列表非常特定的产品名称,并且唯一可能出现在标签内的地方在这样的链接之内。

解决方案

唯一的可靠的方式是逐步完成每个子孙后代,如果是文本节点,则运行替换。



实现: / p>



做你你不仅冒着无意中替换实际的HTML的风险,还可以擦除目标元素中的任何DOM元素和任何相应的事件处理程序。


Thanks to Chetan Sastry I have this Regex code to parse my page for a list of words and add the TM to them.

var wordList = ["jQuery UI", "jQuery", "is"];
var regExp = new RegExp("\\b" + wordList.join("\\b|\\b") + "\\b", "g");
var $elem = $("#divWithText");
$elem.html($elem.html().replace(regExp, "$&&trade;"));

This Regex is almost what I need. However, with a link that looks like:

<a href="/0/products/jQuery">jQuery</a>

It ends up appending the TM to the jQuery inside of the href and NOT the one between the tags.

Can anyone help out with this?

The list of words that I'll be looking for is very specific product names, and the only place they might appear inside of a tag is inside of a link like this.

解决方案

The only reliable way to accomplish this is to step through each child descendant and, if it's a text node, then run the replacement.

Implementations:

Doing it your way, not only do you run the risk of inadvertently replacing actual HTML, but you also wipe any DOM elements within the targeted element, and any corresponding event handlers.

这篇关于正则表达式在页面上找到包含内部标签的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆