Steve Steve - 22 days ago 5
Javascript Question

Regex to wrap email address in mailto from a string

Want to turn

some text email@address.com
into
some text <a href="mailto:email@address.com">email@address.com</a>


Below is the regex I'm using in replace:

'some text email@address.com'.replace(/([a-zA-Z0-9_\.\-]+)@(([[0-9]{1,3}' + '\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.' + ')+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)/gi, '<a href='mailto:$1'>$1</a>');


The regex is not working properly, please help.

Answer

As suggested by @Toto, you can use this regex \S+@\S+ to include every possible (and non-possible) characters in the email excluding the space.

(\S+@\S+)

If you want to include only English characters a-z, numbers 0-9, dots ., underscores _, and dashes - . You can do it this way:

([\w\.\-]+@\w+\.\w+)

If you want to add to the previous one every possible character from any language à è ì ò ù, and at the same time, exclude special characters % ^ & *, you can use \pL as follows:

([\w\.\-\pL]+@\w+\.\w+)

Demo for the last Regex:

    var Email = "some text email@address.com.";
    Email = Email.replace(/([\w\.\-\pL]+@\w+\.\w+)/g, '<a href=mailto:$1>$1</a>');
    document.write (Email);