How can I replace a match only at a certain position inside the string?

后端 未结 5 1877
盖世英雄少女心
盖世英雄少女心 2020-12-06 02:43

So, I have a function which has two params: string and match index to replace and i need to replace only match with that index. How can i do that?

Example:

5条回答
  •  既然无缘
    2020-12-06 03:08

    For those like me who find regex to be cryptic, here is "pure JavaScript" way as well:

    function CustomReplace(strData, strTextToReplace, strReplaceWith, replaceAt) {
        var index = strData.indexOf(strTextToReplace);
        for (var i = 1; i < replaceAt; i++)
            index = strData.indexOf(strTextToReplace, index + 1);
        if (index >= 0)
            return strData.substr(0, index) + strReplaceWith + strData.substr(index + strTextToReplace.length, strData.length);
        return strData;
    }
    

    Usage:

    var mystr = 'a_a_a_a_a';
    var newstr = CustomReplace(mystr, "_", "__", 2); //replace the second appearance
    

    Live test case: http://jsfiddle.net/tXx5n/2/

提交回复
热议问题