How do I replace a character at a particular index in JavaScript?

后端 未结 24 2111
孤城傲影
孤城傲影 2020-11-21 07:23

I have a string, let\'s say Hello world and I need to replace the char at index 3. How can I replace a char by specifying a index?

var str = \"h         


        
24条回答
  •  逝去的感伤
    2020-11-21 08:08

    You can use the following function to replace Character or String at a particular position of a String. To replace all the following match cases use String.prototype.replaceAllMatches() function.

    String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
        var retStr = this, repeatedIndex = 0;
        for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
            if (repeatedIndex == 0 && x == 0) {
                repeatedIndex = retStr.indexOf(matchkey);
            } else { // matchIndex > 0
                repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
            }
            if (x == matchIndex) {
                retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
                matchkey = null; // To break the loop.
            }
        }
        return retStr;
    };
    

    Test:

    var str = "yash yas $dfdas.**";
    
    console.log('Index Matched replace : ', str.replaceMatch('as', '*', 2) );
    console.log('Index Matched replace : ', str.replaceMatch('y', '~', 1) );
    

    Output:

    Index Matched replace :  yash yas $dfd*.**
    Index Matched replace :  yash ~as $dfdas.**
    

提交回复
热议问题