Aug
09
2010

Use jQuery to Replace a Word with a Link

by   |  Posted in Tutorials  |  5 comments

If you use a word multiple times on your site and you don’t feel like going through all your posts to replace every instance of it, you can use jQuery to search your page and do the replacing for you. I wanted to replace a word throughout an entire site with a link and all it took was a small piece of code.

If you don’t already have jQuery loaded into your page, include this before your closing <head>.

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>

That will load up jQuery from Google.

Now you just need to include this in your site’s footer, before the closing <body>. (Why in the footer? Because including your JavaScript after all of your code is the efficient way to do it.)

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

Since jQuery doesn’t have a core function for replacing text, we will use the JavaScript replace() function. The i after the slash makes the search and replace case-insensitive, and the g makes it global.

I have the script working on this page to replace every instance of the word jQuery with a link to the jQuery Web site.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , , , , , , , , , , , , ,

Short URL: http://bit.ly/c8I8fT

Discussion 5 Comments

  1. diseƱo web on September 3, 2010 at 2:58 pm

    May this work with my wp blog? How do I implement it?

  2. myst on October 30, 2010 at 8:37 pm

    Hi. Can we make multiple words to replace & how do this sample via external file??

  3. Somebody on February 15, 2011 at 11:13 am

    Hey… great work!
    But I’ve got one question, (how) can i replace the word “jQuery” with a variable in the same function?! :
    (function($) {
    $.fn.tst = function(text) {
    var text = “tst”;
    var where = $(“body”);
    where.html(where.html().replace(/ var text /ig, replacewith));
    }
    })(jQuery);

  4. Somebody on February 15, 2011 at 12:06 pm

    Answered the question myself:

    var nre = new RegExp(text, "ig");
    where.html(where.html().replace(nre, replacewith));
  5. miscky on February 15, 2011 at 6:42 pm

    Nice work!
    I have a question. How can I avoid it from being replaced the text between “a” tag?

    Thanks!