Targeting a specific word using JavaScript and jQuery

Ever needed to target a specific word in a paragraph?  Using a little jQuery you can do just that…

Say you have the following paragraph of text:

John Ipsum rule britannia lorem fish and chips ipsum going to the loo cheers mate crumpets mate off to the pub good day john harry potter cup of tea cup of tea crumpets God save the queen jolly good show rule britannia cheerio! bangers and mash going to the loo arse cheers John cheers mate bloody hell crumpets harry potter bangers and mash hello chaps fish and chips harry potter bollocks toodle pip fish and chips cup of tea off to the pub cheers mate arse tosser knackered ron weasley tosser toodle pip toodle pip fish and chips God save the queen bloody hell rule britannia bollocks john bangers and mash bangers and mash ron weasley

But you want to wrap every instance of the word John in a span tag so that you can style it differently. You can use the following JavaScript to do so:

var oldString = 'john',
newString = '<span>John</span>',
newText = $('p').text().replace(RegExp(oldString,"gi"),newString);

$('p').html(newText);

​Here’s a JS Fiddle so that you can see it in action: http://jsfiddle.net/trtcN/546/

16 much appreciated responses...

  1. kate says:

    Hi,
    this is a nice little script, thank you very much for posting it:)
    However this works only for instances-children of ‘p’ elements.
    Being new to jquery I tried to change the containing element from “p” to “body” or even “div” as follows:

    var tablet = $(‘div’).text().replace(/Tablet PC /g,”Tablet PC “);
    $(‘div’).html(tablet);
    }

    but it messes up the whole layout, just displaying ALL text at once – ignoring css and layout/formatting.

    What am I doing wrong?

    Thanks,
    kate

    • johndoesdesign says:

      Hey Kate,

      Basically $(‘div’).html(tablet); replaces all of the HTML inside of the div with the string which is contained inside of the ‘tablet’ variable.

      If you want to apply the search and replace to multiple elements you can use jQuery’s ‘each’ function to filter through all occurances of specified tags like so: http://jsfiddle.net/trtcN/14/

      Or you could give the elements you want to replace a class and only target those specific elements, like so: http://jsfiddle.net/trtcN/13/

      Hope that helps!

      John

  2. Phil says:

    Hi, this is a very cool piece of script. I was wondering if you could help me out here as, like Kate, I am new to JQuery.

    Here is my markup for the jquery;

    $('.moduletablehomeblock3 > h3').each(function(){
    var changethis = $(this).text().replace(/MULTIPLE /g,"MULTIPLE SCLEROSIS ");
    $(this).html(changethis);
    });
    $('.moduletablehomeblock1 > h3').each(function(){
    var alter = $(this).text().replace(/ORGANIZATION /g,"OUR ORGANIZATION ");
    $(this).html(alter);
    });

    $('.moduletablecolumn_smaller > h3').each(function(){
    var changethisalso = $(this).text().replace(/HELP /g,"HELP US ");
    $(this).html(changethisalso);
    });

    I noticed in the JSfiddle there is an OnLoad function. What exactly does that mean? I have this code placed in the website I have mentioned in this comment submission.

    Any help is appreciated.
    Thanks, Phil

    • John B says:

      Hey Phil,

      I’d be happy to help. Is your code above working? I’m unclear on what you need help with exactly. Are you able to put it into a JSFiddle with an example of the HTML markup you’re trying to manipulate, then I can help you with any issues you might have.

      The onload function just means that the code inside it fires once the targeted element has fully loaded into the DOM (on your web page). So $(‘img.dog’).onload(); only fires once the image of a dog has loaded.

      John

  3. Karen says:

    Great piece of code, thank you. I’m just playing around in your JSFiddle (how cool is that site?!) as I’m trying to get this to work for a table. I can’t quite get it to work. I’m in your http://jsfiddle.net/trtcN/13/ and using .replace as a table class.

    Any help appreciated. Thanks so much.

    HTML:

    Firstname
    Lastname
    Points

    John
    Jackson
    94

    • John B says:

      Hey Karen, if you could save your JSFiddle and send me the link to it so that I can see the exact code you’re using then I’d be happy to help!

      PS. If you think JSFiddle is cool then check out CodePen.

  4. Webbro says:

    This is genius, I love it, thank you for sharing, I just made good use of this code and will be very handy in the future.

    Webbro Web Designs
    Danny

    • John B says:

      Glad to hear it was useful Danny :)

  5. Kristian Lawrence says:

    Hi there,
    Thankyou so much. This mostly worked perfectly. Except it has stripped any text of links they have. Any idea why that may have happened.
    Here is my CodePen: http://codepen.io/anon/pen/AhotL

    Thanks again!

  6. gripper says:

    Try this:

  7. Razvan says:

    Great piece of code. I have a question, nevertheless:

    How do I use variable instead of “John”, and how do I replace “John” and “john” with “John” (make the script case insensitive)?

    Thank you!

    • John B says:

      Hey Razvan,

      I’ve made a change to the JSFiddle so it will work with variables and is case insensitive. Let me know if this works for you: http://jsfiddle.net/trtcN/546/

      John

Feel free to add your comment..

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>