Javascript替换电子邮件地址

Javascript替换电子邮件地址,javascript,jquery,replace,Javascript,Jquery,Replace,快速提问-为什么这不起作用 我很确定我已经测试了所有的东西,但都没有用。我试图基本上添加邮件链接到任何可以找到的电子邮件 它不会用mailto标签替换电子邮件链接 谢谢, 哈利 $(文档).ready(函数(){ 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); //待办事

快速提问-为什么这不起作用

我很确定我已经测试了所有的东西,但都没有用。我试图基本上添加邮件链接到任何可以找到的电子邮件

它不会用mailto标签替换电子邮件链接

谢谢, 哈利

$(文档).ready(函数(){
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);
//待办事项-当已经有mailto链接时不要尝试,可能只需将mailto添加到正则表达式中即可。
对于(变量i=0;i
我想你应该这样做:

 var result = bodyText.replace(email_regex,'<a href="mailto:$1">$1</a>');
 console.log(result); // This two lines are enough.
var result=bodyText.replace(email_regex.);
console.log(结果);//这两行就够了。
完整代码:

$(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.
});
$(文档).ready(函数(){
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.);
console.log(result);//这两行就足够了。
});

第一个问题是
g
标志不能一次检索所有匹配项。它只允许在循环中调用
exec()
。您需要:

var match;
while ( (match = email_regex.exec(bodyText)) !==null) {
}
bodyText= bodyText.replace(match[i], '<a href="mailto:' + match[i] + '">' + match[i] + '</a>');
第二个问题是
replace()
不会修改原始字符串。您需要:

var match;
while ( (match = email_regex.exec(bodyText)) !==null) {
}
bodyText= bodyText.replace(match[i], '<a href="mailto:' + match[i] + '">' + match[i] + '</a>');
参考:


嘿,哈利,什么不起作用了?我已经更新了OP-它没有用mailto a标签替换电子邮件链接。很高兴能帮上忙;)+1但是,从技术上讲,这并不能回答为什么这个问题不起作用;-)此regexp不起作用,邮件后包含点的文本将在链接中包含点,此效果更好:
/([a-zA-Z0-9.\u-]+@[a-zA-Z0-9.\u-]+\.[a-zA-Z0-9.\u-]+)(?