0

I want to write a javascript function to read all the email addresses and make it to link. for example if it finds [email protected] replace it with <a href="mailto:[email protected]">[email protected]</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:[email protected]">[email protected]</a>"

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

[email protected]">[email protected]

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.

1
  • 4
    That's why you should not apply the expression on the raw HTML string, but recursively iterate over all DOM nodes and only apply the expression to text nodes. Commented Feb 23, 2013 at 11:29

1 Answer 1

2

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 = ' [email protected] <a href="mailto:[email protected]">[email protected]</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:[email protected]">[email protected]</a> <a href="mailto:[email protected]">[email protected]</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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.