简体   繁体   English

Javascript 替换电子邮件地址

[英]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.我试图基本上将 mailto 链接添加到可以找到的任何电子邮件。

It's not replacing the email links with the mailto a tags.它不会用 mailto a 标签替换电子邮件链接。

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);
});

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.
});

The first problem is that the g flag does not retrieve all matches at once.第一个问题是g标志不会一次检索所有匹配项。 It merely allows to call exec() in a loop.它只允许在循环中调用exec() You'd need:你需要:

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

The second problem is that replace() does not modify the original string.第二个问题是replace()不会修改原始字符串。 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:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM