Is there a way to add code to every instance of a regex on the fly?

Say I have a block of text, and I want to replace each instance of the word "the" with an indexed number.

For instance...

"The Great White Shark is the father of bite theory."

will become ...

"0 great white shark is 1 fa2r bite 3ory."

I am looking for something like: myText.match (/ The / g) .each (function (s) {//?});

Greetings are welcome.

+3
source share
2 answers

Example: http://jsfiddle.net/sYQgb/1/

var i = -1;
myText = myText.replace(/the/gi, function(){ return ++i; });
+5
source
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+" &nbsp;</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  

If you want to play: http://jsfiddle.net/QFUWG/

0
source

Source: https://habr.com/ru/post/1792068/


All Articles