开发者

Regex to find word on page including inside tags

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, "$&™"));

This Regex is almost what I need. However, with a link that looks li开发者_Go百科ke:

<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:

  • http://benalman.com/projects/jquery-replacetext-plugin/
  • http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/

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.


J-P linked to some good utilities for the job.

With straight jQuery:

$elem
  .contents()
  .filter(function() {
    return this.nodeType == Node.TEXT_NODE;
  })
  .each(function(){
    $(this).text($(this).text().replace(regExp, "$&&trade;"));
  });

(SEE How do I select text nodes with jQuery?)


what about adding "jQuery</a>" and "jQuery UI</a>" to your list of search terms? (You'll need to escape the special characters for RegEx to work properly but it might be an easier (if less elegant) solution.)


If you are only trying to replace words within a link then the following should work:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜