0

我想编写一个 javascript 函数来读取所有电子邮件地址并使其链接。例如,如果它发现test@example.com将其替换为<a href="mailto:test@example.com">test@example.com</a>.

我正在使用这个:

document.body.innerHTML = document.body.innerHTML.replace(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi, <a href="mailto:$1">$1</a>'));

它适用于简单的电子邮件地址。

但问题是如果电子邮件地址已经采用这种格式:

"<a href="mailto:test@example.com">test@example.com</a>"

然后它不起作用。输出变得像这样错误:

test@example.com">test@example.com

请建议我任何解决方案。所以该功能可以正常工作。

或任何其他使简单电子邮件成为链接的功能,如果电子邮件已经在 mailto: 链接形式中,则什么也不做。

4

1 回答 1

2

这是一种仅在电子邮件之前的字符不是 , 或 时进行>替换的:方法。它基本上是一种模拟负面回顾的方式"'

var str = ' test@example.com <a href="mailto:test@example.com">test@example.com</a> ',
    rex = /(["'>:]?)([\w.-]+@[\w.-]+\.[\w.-]+)/gi;

str = str.replace( rex, function ( $0, $1 ) {
    return $1 ? $0 : '<a href="mailto:' + $0 + '">' + $0 + '</a>';
});

// " <a href="mailto:test@example.com">test@example.com</a> <a href="mailto:test@example.com">test@example.com</a> "

\w相当于[a-zA-Z0-9_]

要更具体地了解何时阻止更换,您可以将rex上面的内容更改为类似

rex = /(<a href(?:(?!<\/a\s*>).)*)?([\w.-]+@[\w.-]+\.[\w.-]+)/gi;

<a href如果电子邮件出现在和之间,这只会阻止替换</a>

这些正则表达式解决方案都不是无懈可击的,但在某些情况下它们可能已经足够好了。

于 2013-02-23T11:59:27.610 回答