0

I want to replace specific words (laptop, asus, acer) with links (test.com/l12, test.com/13, test.com/14) using jQuery. I found this function

<script type="text/javascript">
(function($) {
          var thePage = $("body");
          thePage.text(thePage.html().replace(/laptop/ig, '<a href="http://test.com/laptop">laptop</a>')); 
})(jQuery)
</script>

but the problem is that it replaces laptop word in existing urls (creating urls like test.com/test.com/laptop-review if the url was test.com/laptop-review) and all the laptop html (html ids, classes, urls etc) on the page is destroyed.

Thank you

kingbt
  • 19
  • 1
  • 7

2 Answers2

3

You could do:

$('body *').each(function(){
     var txt = $(this).text();

    txt =  txt.replace('laptop', '<a href="http://test.com/laptop">laptop</a>');


    $(this).html(txt);
});

fiddle http://jsfiddle.net/LXw6P/

EDIT of course you could make this a function and reuse it:

var updateTxt = function(stringToReplace){
    var replaceText = '<a href="http://test.com/'+stringToReplace'+">'+stringToReplace+'</a>';
    $('body *').each(function(){
       var txt = $(this).text();

        txt =  txt.replace(stringToReplace, replaceText);


        $(this).html(txt);
    });
}

use it:

updateTxt('laptop');
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
  • That is good but an exhausting task to loop through every element. :) maybe adding a special class and span to the special words could ease the work load :) – Val Sep 29 '11 at 08:57
1

You could try using the jQuery text replace plug-in - http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/

The plug-in should ignore HTML mark-up and only change 'text' values.

Further details are given in this question - How do I do a case insensitive search for a word and convert it to a hyperlink using jquery?

Community
  • 1
  • 1
ipr101
  • 24,096
  • 8
  • 59
  • 61