gpt4 book ai didi

Javascript 正则表达式 : surround @_____, #____,和 http ://______ with anchor tags in one pass?

转载 作者:搜寻专家 更新时间:2023-11-01 04:28:00 30 4
gpt4 key购买 nike

相关(但略有不同):

Surrounding all instances of @________, #___________, and http://_________ with anchor tags?

我想包围 @_______ 的所有实例, #________ , 和 http://________一次性使用 anchor 标签。

例如,考虑这条 Twitter 消息:

The quick brown fox @Spreadthemovie jumps over the lazy dog #cow http://URL

使用所需的正则表达式模式运行它会产生:

The quick brown fox <a href="a">@Spreadthemovie</a> jumps over the lazy
dog <a href="b">#cow</a> <a href="c">http://URL</a>

只包围以 @ 开头的单词, #http://这样dog@gmail.com不会变成 dog<b>@gmail.com</b> .

最佳答案

var sample = "@sample";
sample = sample.replace(/[^\s+-+.+](@\w+|#\w+|http://[\w\./]+)[$\s+-+.+]/g, "<a>$1</a>");

$1 插入匹配的字符串。

使用函数(我针对您的特定情况推荐):

var sample = "@sample";
sample = sample.replace(/[^\s+-+.+](@\w+|#\w+|http://[\w\./]+)[$\s+-+.+]/g, function(str) {
var href="";
if(str.indeoxOf("#") !== -1)
href=str;
else if(str.indexOf("@") !== -1)
...
return "<a href="+href+">"+str+"</a>";
});

当您想要更好地控制时,使用函数是个好主意。如果您希望链接在其 anchor 标记中具有不同的 href,则这种方式更容易。

查看更多here at MDC .

关于Javascript 正则表达式 : surround @_____, #____,和 http ://______ with anchor tags in one pass?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1181204/

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