Skip to content

Instantly share code, notes, and snippets.

@freshsnippets
Created April 3, 2012 19:21
Show Gist options
  • Save freshsnippets/2294872 to your computer and use it in GitHub Desktop.
Save freshsnippets/2294872 to your computer and use it in GitHub Desktop.
JavaScript: jQuery replaceText
jQuery.fn.replaceText = function( search, replace, text_only ) {
return this.each(function(){
var node = this.firstChild,
val,
new_val,
remove = [];
if ( node ) {
do {
if ( node.nodeType === 3 ) {
val = node.nodeValue;
new_val = val.replace( search, replace );
if ( new_val !== val ) {
if ( !text_only && /</.test( new_val ) ) {
$(node).before( new_val );
remove.push( node );
} else {
node.nodeValue = new_val;
}
}
}
} while ( node = node.nextSibling );
}
remove.length && $(remove).remove();
});
};
//credit: http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/
//usage: jQuery('#container').replaceText('Stuff to replace', 'replaced stuff');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment