Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript函数从网页中查找电子邮件地址_Javascript_Regex - Fatal编程技术网

Javascript函数从网页中查找电子邮件地址

Javascript函数从网页中查找电子邮件地址,javascript,regex,Javascript,Regex,我想写一个javascript函数来读取所有的电子邮件地址并使其链接。 例如,如果它发现test@example.com将其替换为 我用的是: 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>')); 请给我建议任何解决办法。因此,该函数可以

我想写一个javascript函数来读取所有的电子邮件地址并使其链接。 例如,如果它发现
test@example.com
将其替换为

我用的是:

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>'));
请给我建议任何解决办法。因此,该函数可以正常工作


或任何其他功能,使简单电子邮件成为链接,如果电子邮件已经是mailto:link格式,则不做任何操作。

这里有一种方法,仅当电子邮件前的字符不是
,则只进行替换。这基本上是一种模拟负面外观的方法

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> "
只有当电子邮件出现在
之间时,这才会阻止替换


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

这就是为什么不应该在原始HTML字符串上应用表达式,而应该递归地迭代所有DOM节点,只将表达式应用于文本节点。
test@example.com">test@example.com
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> "
rex = /(<a href(?:(?!<\/a\s*>).)*)?([\w.-]+@[\w.-]+\.[\w.-]+)/gi;