Ever needed to target a specific word in a paragraph? Using a little jQuery you can do just that…
Say you want to wrap every instance of the word ‘John’ in a span tag so that you can style it differently, use:
var john = $('p').text().replace(/John /g,"<span>John </span>");
$('p').html(john);
Here’s a JS Fiddle so that you can see it in action: http://jsfiddle.net/trtcN/3/



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
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