用JS把URL链接地址自动转化成超链接形式

用javascript语言和正则表达式实现的函数

if (!content) {
    return "";
}
let urlPattern = /(https?:\/\/|www\.)[a-zA-Z_0-9\-@]+(\.\w[a-zA-Z_0-9\-:]+)+(\/[\(\)~#&\-=?\+\%/\.\w]+)?/g;
content = content.replace(urlPattern, function (match) {
var href = match;
if (match.indexOf("http") == -1) {
    href = "http://" + match;
}
return '<a target="_blank" href="' + href + '">' + match + "</a>";
});
return content;
}

分享到:
赞(0)