将所有电子邮件匹配包含在带有标签的字符串中

时间:2013-01-07 07:49:04

标签: javascript regex replace

我一直尝试使用不同的功能来替换blahhhh@blahhh.blahhh DIV中的任何contentEditable,但没有成功。正则表达式存在问题,或者[String].replaceAll不是Chrome中的现有原型,因此我需要使用我在网络上找到的任何replaceAll

使用自定义模式替换字符串中所有电子邮件的跨浏览器(Chrome / WebKit / Moz)算法应该是什么?

1 个答案:

答案 0 :(得分:3)

实际上,

replaceAll不是标准函数,但正则表达式应该起作用:

像这样简单:

  

[A-Z0-9 ._%+ - ] + @ [A-Z0-9 .-] + [A-Z] {2,}

已经可以很好地运作了:

var s = "sample@mail.com is a sample email address with an @, as is some.mail@some.government";
s.replace(/([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,})/ig, '<tag>$1</tag>');
// "<tag>sample@mail.com</tag> is a sample email address with an @, as is <tag>some.mail@some.government</tag>";

# Match:
# (              --> Start group
# [A-Z0-9._%+-]+ --> one or more characters within the specified range,
# @              --> Followed by an `@`,
# [A-Z0-9.-]+    --> Followed by some more characters,
# \.             --> Followed by an dot,
# [A-Z]{2,}      --> followed by 2 or more letters,
# )              --> End group.
# ig             --> (i)gnore case, (g)lobal.
# In the replacement:
# $1             --> Content of the first pair of `()`