Julien
Julien

Reputation: 5729

Find and Replace with JQuery

I am trying to use JQuery to search and replace all instances of a given string. JQuery was the only method I found which doesn't force-reload the whole page. This is what I have right now:

<script>
$("*").each(function () { 
   if ($(this).children().length == 0) { 
      $(this).html($(this).html().replace('0101','0102')); 
   } 
});
</script>

Right now, this replaces most instances of 0101 with 0102 on the page, but it does not replace instances within href links. Does anyone know why? I really need this to find/replace the whole document, through and through.

Upvotes: 0

Views: 2722

Answers (2)

jwueller
jwueller

Reputation: 30996

I believe that your problem lies in the use of .replace(). If you use a string as the search-value, only the first occurrence is replaced. You need to use a regular expression with the global-flag for this:

$(this).html($(this).html().replace(/0101/g,'0102')); 

Upvotes: 0

Rigobert Song
Rigobert Song

Reputation: 2784

Add this

$(this).attr('href', $(this).attr('href').replace('0101','0102'));

The .html() method is only going to replace the html within an element.

.attr() allows you to access the attributes of an element which of course the href is.

Upvotes: 1

Related Questions