gpt4 book ai didi

javascript - 用标签包围字符串中的所有电子邮件匹配项

转载 作者:行者123 更新时间:2023-11-30 10:35:35 26 4
gpt4 key购买 nike

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

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

最佳答案

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 `()`

关于javascript - 用标签包围字符串中的所有电子邮件匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14191881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com