JavaScript: String.replace()

8 Dec

Today I had to help out my friend with replace any email address with < email address >

Here is the easiest solution I could come up with:

var myString = “My email address rajesh.segu@abc.com”;

function replaceEMail(){
return “<”+arguments[0]+”>”;
}

myString = myString.replace(  /([0-9a-zA-Z]+[-._+&amp;])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}([\w/_\.]*(\?\S+)?)/ig, replaceEMail);

myString here becomes “My email address <rajesh.segu@abc.com>”.

The best part in this solution is that you could pass a function to the string.replace() which would make things like replacing regex’s intelligently.

One Response to “JavaScript: String.replace()”

  1. Sricharan 02. Jul, 2010 at 5:42 pm #

    Really good one ! hope i can use it some were in my proj..

Leave a Reply