CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

String.ReplaceAll function in JavaScript
Submitted By Satheesh Babu B
On 1/8/2009 7:39:12 AM
Tags: CodeDigest,JavaScript  

String.ReplaceAll function in JavaScript

 

The string functions in JavaScript string object does not have a method to replace all string found in a string. To replace all string pattern found in a string we need to write our own script.

 

The below script will help us doing that.

 

function ReplaceAll(Source,stringToFind,stringToReplace){

  var temp = Source;

    var index = temp.indexOf(stringToFind);

        while(index != -1){

            temp = temp.replace(stringToFind,stringToReplace);

            index = temp.indexOf(stringToFind);

        }

        return temp;

}

 

To call this function similar to an inbuilt function, we need to define the ReplaceAll function protype. Refer the below script,

 

String.prototype.ReplaceAll = 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;

    }

 

To call this function,

function replacecall()

    {

        var name = "I Love Dotnet";

        alert(name);

        alert(name.ReplaceAll(" ","_"));

    }

 

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..