Is there a way to add code to each instance of a regex match on the fly?
Let's say I have a block of text and I want to replace each instance of the word "the" with an indexed number.
For example...
"The great white shark is the father of bite theory."
would become.开发者_StackOverflow社区..
"0 great white shark is 1 fa2r of bite 3ory."
I'm looking for something like: myText.match(/the/gi).each(function(i){ //? });
jquery solutions welcome.
Example: http://jsfiddle.net/sYQgb/1/
var i = -1;
myText = myText.replace(/the/gi, function(){ return ++i; });
function replaceText(text, splitArg) {
//var text ="axaxa";
var parts = text.split(splitArg);
var replaced = "";
var part;
for (var i=0;i<parts.length;i++) {
part = parts[i]
if(i > 0)
replaced += i-1;
replaced+=part;
}
return replaced;
}
function writeLine(text) {
document.write("<p>"+text+" </p>");
}
writeLine(replaceText("axa", "x"));
writeLine(replaceText("axaxa", "x"));
writeLine(replaceText("axaxxa", "x"));
writeLine(replaceText("axaxxa", /x+/));//**using a regex!**
writeLine(replaceText("", "x"));
writeLine(replaceText("aa", "x"));
//output:
//a0a
//a0a1a
//a0a12a
//a0a1a
//
//aa
In case you want to play around: http://jsfiddle.net/QFUWG/
精彩评论