Cleo Cleo - 8 days ago 8
jQuery Question

JQuery .replace function overlapping similar phrases

I'm using the jQuery .replace function to turn all occurrences of certain words into links using this code:

$.each($('p'), function(i,e) {
$(e).html($(e).html().replace(/candy/g,'<a href="http://www.rantlifestyle.com/wp-content/uploads/2014/06/First.jpg">candy</a>'));
})


The problem is that some of the phrases contain the same letters, so when I have two that conflict, the words don't get replaced correctly. For instance, if I used this code as well as the code above:

$.each($('p'), function(i,e) {
$(e).html($(e).html().replace(/can/g,'<a href="https://thumbs.dreamstime.com/x/empty-tin-can-7151872.jpg">can</a>'));
})


Then it tries to replace the letters 'candy' and 'can' with each link I've specified in the one occurrence of the word 'candy.'

Is there a way to specify that I want the replace function to work with specific phrases?

Side note, I tried to make a simple example of this on jsfiddle and it's not working. Maybe that has something to do with my issue?

Thanks!

Answer

Here you go, you need to use this to match whole words:

$.each($('p'), function(i,e) {
  $(e).html($(e).html().replace(/\bcandy\b/,'<a href="http://www.rantlifestyle.com/wp-content/uploads/2014/06/First.jpg">candy</a>'));
})

    $.each($('p'), function(i,e) {
      $(e).html($(e).html().replace(/\bcan\b/,'<a href="https://thumbs.dreamstime.com/x/empty-tin-can-7151872.jpg">can</a>'));
})

https://jsfiddle.net/bndeL2q6/2/