Friday, September 05, 2008

Replace Chars in String - prototype example

An elegant way to replace certain chars from a string with new ones:

// Custom method for replacing certain chars from a string with new ones
function ReplaceChars(oldValue,newValue) {
var newText = this.split(oldValue);
newText = newText.join(newValue);
return newText;

}

// Attach the custom method to string object
String.prototype.Replace = ReplaceChars;

// Usage
var myString = "Hello World!";
alert(myString.Replace("o","0")); // will output "Hell0 W0rld!"

0 comentarii: