Steve Steve - 7 months ago 38
Javascript Question

Regex to wrap email address in mailto from a string

Want to turn

some text
some text <a href=""></a>

Below is the regex I'm using in replace:

'some text'.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.


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.


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


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:


Demo for the last Regex:

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