Skip to content

Instantly share code, notes, and snippets.

@senko
Created July 28, 2011 21:14
Show Gist options
  • Save senko/1112574 to your computer and use it in GitHub Desktop.
Save senko/1112574 to your computer and use it in GitHub Desktop.
DOM text search/replace plugin for jQuery.
(function($){
$.fn.textReplace = function(map, patterns) {
map = map || {};
patterns = patterns || [];
$('*', this).contents().filter(function() {
return ((this.nodeType == 3));
}).each(function() {
var old_text = $.trim(this.nodeValue);
var new_text;
if (map.hasOwnProperty(old_text)) {
new_text = map[old_text];
if (typeof new_text == "function") {
new_text = new_text(this);
}
} else {
for (var i in patterns) {
var pattern = patterns[i][0];
var replacement = patterns[i][1];
if (old_text.match(pattern)) {
if (typeof replacement == "function") {
new_text = replacement(this);
} else {
new_text = old_text.replace(pattern, replacement);
}
break;
}
}
}
if (new_text != undefined) {
this.nodeValue = new_text;
}
});
}
})(jQuery);
@senko
Copy link
Author

senko commented Jul 28, 2011

See it in action: http://jsfiddle.net/8w55h/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment