Extract all Email addresses from a string


  I want to extract All the email Addresses from a string. Can you guys help me in doing that. Thanks in advance ...

Are you sure you want this with JavaScript? At least I don’t know that it is possible to extract all the email address from a string with JavaScript. What is the problem to be done it with some server side languages like PHP.

Yes I want to do it with javascript. And I have a specific requirement which has to be completed in Javascript.

This is not validation, just extraction, so a regex along the lines of /\b([^\s]+@[^\s]+)\b/g would do the job.

If need be, you would run each extracted email through a validation process as well.

Just curious to know how JavaScript extracts all the email addresses from a string? Can you please write a piece of code if you don’t mind?


I just googled and found the following function at http://javascript.internet.com/forms/extract-email.html and which seems works perfectly:

	function findEmailAddresses(StrObj) {
		var separateEmailsBy = ", ";
		var email = "<none>"; // if no match, use this
		var emailsArray = StrObj.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9._-]+)/gi);
		if (emailsArray) {
			email = "";
			for (var i = 0; i < emailsArray.length; i++) {
				if (i != 0) email += separateEmailsBy;
				email += emailsArray[i];
		return email;

The code that you have there take my initial idea and fleshes it out into good working code. Stick with that.

The code worked. Thanks Rajug and all others