Monthly Archives: September 2013

Quick Text replace jQuery

Ever find yourself needing to target specific text inside of an element and wrap it so that you can change it? Well here is a quick jQuery regex snippet to help you with just that.

var text = 'I want text';

$( 'TAG YOU WANNA GRAB' ).html( function ( i, html ) {
    var regexp, replacement;

    regexp = RegExp( '(' + text + ')', 'gi' );
    replacement = '<span class="highlight">$1</span>';

    return html.replace( regexp, replacement );

So how does this work?

Well first off we create a variable called “text”. That variable contains the text that we are looking for. In this example it is “I want text’. So perhaps in your code you have this

<p>I want text to show off to all of my friends<p>

Next we pull the Javascript RegExp object to look for a matched set of data. In this case it is defined in our variable “text”. We add the ‘gi’ to search ‘g’to find all the matches(‘not just stopping after the first match) and ‘i’ to be case-insensitive.
We then define our replacement variable to equal the span tag and keep the $i (placeholder) text. (in this case it is the text we were looking for.
Then it just a matter of returning the .html values we need.

And here is your result

<p><span class="highlight">I want text<span> to show off to all of my friends<p>