简体   繁体   中英

Javascript function to find email address from a webpage

I want to write a javascript function to read all the email addresses and make it to link. for example if it finds test@example.com replace it with <a href="mailto:test@example.com">test@example.com</a> .

I am using this:

document.body.innerHTML = document.body.innerHTML.replace(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi, <a href="mailto:$1">$1</a>'));

It work fine for simple email addresses.

But the problem is if the email address already in this format:

"<a href="mailto:test@example.com">test@example.com</a>"

Then It does not work. The output becomes wrong like this:

test@example.com">test@example.com

Please suggestive me any solution. So the function can work fine.

Or any other function to make the simple email a link and if the email is already in mailto: link form then do nothing.

Here is one method which only makes the replacement if a character before the email is not > , : , " or ' . It is basically a way of emulating a negative look-behind

var str = ' test@example.com <a href="mailto:test@example.com">test@example.com</a> ',
    rex = /(["'>:]?)([\w.-]+@[\w.-]+\.[\w.-]+)/gi;

str = str.replace( rex, function ( $0, $1 ) {
    return $1 ? $0 : '<a href="mailto:' + $0 + '">' + $0 + '</a>';
});

// " <a href="mailto:test@example.com">test@example.com</a> <a href="mailto:test@example.com">test@example.com</a> "

\\w is equivalent to [a-zA-Z0-9_] .

To be more particular about when a replacement is to be prevented you could change rex above to something like

rex = /(<a href(?:(?!<\/a\s*>).)*)?([\w.-]+@[\w.-]+\.[\w.-]+)/gi;

This would only prevent a replacement if the email appeared between <a href and </a> .

None of these sort of regex solutions are watertight, but in some circumstances they may be good enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM