admin管理员组

文章数量:1290978

I want to have JavaScript/jQuery code that scan a whole page looking for emails and stores them in an array.

I have a regular expression for email and I know how to check if lets say a textfield has a valid email BUT I have no idea how to scan whole document/page (h1 tags, h2 tags, anchor tags.....) looking for email. Please help

I want to have JavaScript/jQuery code that scan a whole page looking for emails and stores them in an array.

I have a regular expression for email and I know how to check if lets say a textfield has a valid email BUT I have no idea how to scan whole document/page (h1 tags, h2 tags, anchor tags.....) looking for email. Please help

Share Improve this question edited Apr 10, 2014 at 20:58 Jason Aller 3,65228 gold badges41 silver badges39 bronze badges asked Apr 10, 2014 at 19:41 user2982527user2982527 812 silver badges9 bronze badges 2
  • 1 You could get the whole body content, string it and then use a regex to get all the e-mails are actually written in the body. – Morrisda Commented Apr 10, 2014 at 19:47
  • Could you give me some more info about: "get the whole body content and string it" Some code samples would be great – user2982527 Commented Apr 10, 2014 at 19:56
Add a ment  | 

2 Answers 2

Reset to default 8

i think this is what you are looking for:

 function getEmails() {

var search_in = document.body.innerHTML;
string_context = search_in.toString();

array_mails = string_context.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
return array_mails;

}

Short explanation: This function just gets the content of the body, where e-mails should be, makes it a string and then uses a simple regex to get all the matches (/g modifier is applied), case-insensitive (/i modifier is also), that sounds like e-mail text. Then these matches are returned as an array of all of them. var my_emails = getEmails() could be your wondered array.

If you're trying to find email addresses in the source code you can take the whole body of the page and parse them out directly with the match() method.

// assuming you have your regex stored in a variable "regex"
var emails = document.body.match(regex);
for(var i=0; i<emails.length; i++){
    console.log(emails[i]); // or whatever you need to do with them
}

本文标签: javascriptTo find all emails on a pageStack Overflow