Find and replace a string inside another string





11
Date Submitted Thu. Aug. 10th, 2006 2:38 AM
Revision 1 of 1
Syntax Master sundaramkumar
Tags JavaScript
Comments 0 comments
Find and replace a string or character(s) inside another string


//find and replace str
String.prototype.findandreplace = function (find, replace) {
        var myString = this;
        var counter = 0;
        while (counter < myString.length) {
                var start = myString.indexOf(find, counter);
                if (start == -1) {
                        break;
                } else {
                        var before = myString.substr(0, start);
                        var after = myString.substr(start + find.length, myString.length);
                        myString = before + replace + after;
                        var counter = before.length + replace.length;
                }
        }
        return myString;
};

 

Comments

There are currently no comments for this snippet.

Voting