Monday, June 18, 2012

Replace all the matching String in Javascript

Problem: How to replace all the matched String with your String in Javascript?

Solution:
Use replace function of Javascript to replace all Strings in below format.

String.prototype.replaceAllString = function(stringToFind, stringToReplace) {
    var temp = this;
    var index = temp.indexOf(stringToFind);
    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }
    return temp;
}

Use it as below:
var newString = oldString.replaceAll("StringtoBeReplaced", "StringToBeReplacedWith");

No comments:

Post a Comment