Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace email addresses

quick question - Why isn't this working?

I'm pretty sure that I've tested everything to no avail. I'm trying to basically add mailto links to any email that can be found.

It's not replacing the email links with the mailto a tags.

Thanks, Harry

$(document).ready(function() {
    var email_regex = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi;

    var bodyText = $('body').html();
    var match = email_regex.exec(bodyText);
    // To do - Don't try it when there is already a mailto link, can probably just add mailto to the regex.
    for (var i = 0; i < match.length; i++) {
        bodyText.replace(match[i], '<a href="mailto:' + match[i] + '">' + match[i] + '</a>');
        console.log(match[i]);
    }
    $('body').html(bodyText);
    console.dir(match);
});
like image 374
Harry Torry Avatar asked Jul 22 '26 15:07

Harry Torry


2 Answers

You should instead to this I suppose:

 var result = bodyText.replace(email_regex,'<a href="mailto:$1">$1</a>');
 console.log(result); // This two lines are enough.

Full code:

$(document).ready(function() {
    var email_regex = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi;
    var bodyText = $('body').html();
    var result = bodyText.replace(email_regex,'<a href="mailto:$1">$1</a>');
    console.log(result); // This two lines are enough.
});
like image 154
Amit Joki Avatar answered Jul 25 '26 04:07

Amit Joki


The first problem is that the g flag does not retrieve all matches at once. It merely allows to call exec() in a loop. You'd need:

var match;
while ( (match = email_regex.exec(bodyText)) !==null) {
}

The second problem is that replace() does not modify the original string. You'd need:

bodyText= bodyText.replace(match[i], '<a href="mailto:' + match[i] + '">' + match[i] + '</a>');

Still, you could easily get into an infinite loop this way. You'd need to work on a copy:

var newBodyText = bodyText;
...
while ( (match = email_regex.exec(bodyText)) !==null) {
    ...
    newBodyText = newBodyText.replace(...)
}
$('body').html(newBodyText);

Reference:

  • String.replace()
  • RegExp.exec()
like image 22
Álvaro González Avatar answered Jul 25 '26 05:07

Álvaro González



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!