Skip to content

Instantly share code, notes, and snippets.

@tonylegrone
Created July 30, 2010 20:56
Show Gist options
  • Save tonylegrone/501306 to your computer and use it in GitHub Desktop.
Save tonylegrone/501306 to your computer and use it in GitHub Desktop.
jQuery - dynamically wrap words in specific tags
/*
Wrap specified words in the specified tag with jQuery
h1, h2, and h3 are preselected because of the project this was made for.
Separate the words you wish to wrap by the "pipe" symbol.
You should note that this cascades down through all child elements. So you can be as broad or narrow as you want with the selector.
*/
$(document).ready(function(){
var pattern = /\b(of|the|in|and)/gi; // target whole words globally and case insensitive
var replaceWith = '<span>$1</span>'; // wrap in the tag you want
$('h1,h2,h3').each(function(){
$(this).html($(this).html().replace(pattern,replaceWith));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment