I had the same desire not so long ago.
Consider this use (which I consider more powerful and flexible):
//USAGE: var pattern = [ { selectors : ["p",".metoo","em"], find : ["set", "me", "free"], replace : ["#set#", "@ me@ ", ">free<"] }, { selectors : ["h5"], find : ["I", "quick", "easy"], replace : ["^ $1 ^"] //$1 is a token to use matched value } ]; replaceText(pattern);
As you can see, the function accepts an Array objects that define a group of elements, text for searching and replacing. You can install as many as you want.
Some notes:
$1 - will be replaced with the agreed value.replace array must have at least one value - each matched text will be replaced with the corresponding replace text, otherwise the previous one.
Jsnippet demo
And here is the function that implements this:
var replaceText = function(pat) { var ret = []; for (var i = 0; i < pattern.length; i++) { $(pattern[i].selectors.join(",")).text(function(ind,txt){ for (var j=0; j < pattern[i].find.length; j++) { if (typeof pattern[i].replace[j] !== 'undefined') { rep = pattern[i].replace[j].replace("$1", pattern[i].find[j]); } else if (pattern[i].replace.length) { rep = pattern[i].replace[pattern[i].replace.length-1].replace("$1", pattern[i].find[j]); } else { continue; } txt = txt.replace(pattern[i].find[j], rep); } return txt; }); } };
Shlomi hassid
source share