DanH
DanH

Reputation: 25

Replace HREF with what's in between tags (with expressions for emails)

So in a previous question, I was helped out to learn that you can grab what is in between the link tags and place it inside the HREF:

$('a').attr('href', function () {
return 'http://' + $(this).text()})

However, I need a bit more help: I need to identify when the text between the tags is an email to make it into a mailto: href instead.

I don't have much experience with reg expressions, so any advice & direction would be awesome.

Thanks!

Upvotes: 2

Views: 109

Answers (1)

hamed
hamed

Reputation: 8043

First you need to check email with Regular expression. Then pass email to that function for testing. If result is true, put "mailto:" at the beginning of href and if result is false, add "http://" at the beginning.

 if(checkEmail($('a').text()))
     $('a').attr('href', "mailto:"+$('a').text())
 else
    $('a').attr('href', "http://"+$('a').text());



function checkEmail(email) {
  var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
}

Upvotes: 2

Related Questions