Replace strings with other strings in 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! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>