If you have a long string, for example "This is a long string, I want to remove the second string from this string" and you wanted to remove the 2nd instance of the word "string" from the long string using javascript. This method is helpful:
I am sure there are heaps of ways to do this, since I am new to javacript, I found this function helpful
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 txt = CustomReplace(txt,'string','',2);
Hope it helps :)
I am sure there are heaps of ways to do this, since I am new to javacript, I found this function helpful
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 txt = CustomReplace(txt,'string','',2);
Hope it helps :)
No comments:
Post a Comment