简体   繁体   中英

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.

You can use replacer function of replace() function:

 var str = "some text email@address.com"; var regex = /\\w+@\\w+\\.\\w+/gi; var replacedString = str.replace( regex, function(match){ return '<a href="'+match+'">'+match+'</a>'; }); console.log( replacedString ); 

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 az , 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); 

Old question, but I was doing something like this in my code and had to fix a bug where the email address is already wrapped in a mailto link. This was my simple solution to that problem:

var rx = /([mailto:\w.\-pL]+@\w+.[\w.\-pL]+)/gi
return str.replace(rx, function (match) {
  return (match.indexOf('mailto') === 0) ? match : `<a href="mailto:${match}">${match}</a>`
})

The regex optionally matches "mailto:" and the replacer function checks to see if it is in the match, and returns it unmodified if so.

Maybe this will help a fellow google-passer-by.

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