Replace strings with other strings in Javascript

javascript

Here’s a small javascript replace utility function that has been useful to me in the past.

String.prototype.replace = function(strReplaced,strReplacedWith) {
	return this.split(strReplaced).join(strReplacedWith);
}

Here’s an explanation of how to use it in your own scripts.

myString.replace("replace this","with this");

If your string has line breaks, use the following…

myString.replace("\r","<br/>"); //and reverse when displaying in text areas

Hope you find this useful! 🙂