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:>
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/