Skip to content Skip to sidebar Skip to footer

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('\

Solution 1:

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.

Solution 2:

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

With straight jQuery:

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

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

Solution 3:

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

Solution 4:

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

Post a Comment for "Regex To Find Word On Page Including Inside Tags"