javascript - 检测到以 www. 开头的链接问题,用一个元素替换
问题描述
当我匹配http
或者https
我可以将其转换为a
元素时,但由于某种原因,我尝试过的任何东西都不会做出反应,www.
有人可以解释一下吗?
$("[name='text']").each(function(element) {
let str = $(this).text();
if (str.match('http')||str.match('https')) {
var link= str.replace(/(https?:\/\/[^\s]+)/g,"<a href='$1' target='_blank' >$1</a>");
}
if (str.match('www')) {
var link= str.replace(/(www?:\/\/[^\s]+)/g,"<a href='$1' target='_blank' >$1</a>");
}
$(this).html(link);
console.log(link);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div name="text">https://stackoverflow.com/ https link</div>
<div name="text">http://stackoverflow.com/ http link</div>
<div name="text">www.stackoverflow.com/ www link</div>
解决方案
如果有人需要,我根据@charlietfl 的评论为自己写了这个(我认为它涵盖了大多数情况):
$("[name='text']").each(function() {
let str = $(this).text();
//console.log(str);
if (str.match('www') || str.match('http') || str.match('https')) {
var link = "";
if (str.match('http') || str.match('https')) {
link = str.replace(/(https?:\/\/[^\s]+)/g, "<a href='$1' target='_blank' >$1</a>");
}
if (str.match("www") && !str.includes("http")) {
var str2 = str.replace("www", "http://www");
link = str2.replace(/(https?:\/\/[^\s]+)/g, "<a href='$1' target='_blank' >$1</a>");
}
$(this).html(link);
console.log(link);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div name="text">test1 https://stackoverflow.com/ https link</div>
<div name="text">test2 http://stackoverflow.com/ http link</div>
<div name="text">test3 http://www.stackoverflow.com/ http link</div>
<div name="text">test4 https://www.stackoverflow.com/ http link</div>
<div name="text">test5 www.stackoverflow.com/ link</div>
<div name="text">test6 https://www.stackoverflow.com/www-test with another www inside</div>
<div name="text">test7 nolink</div>
推荐阅读
- twilio - 每当通过 Twilio 发送短信时,触发 Twilio 函数以在外部服务(例如 CRM)中写入记录
- python - 在 post 请求中未将 datetime-local 输入的时间传递到服务器
- python - 突出显示包含python中特定点的散点图的一部分
- html - 为什么一个按钮覆盖而另一个没有?
- c - 如何禁用有关在 GCC 中使用弃用获取的警告?
- asp.net - 解决 ASP.NET Core 3.1 API 中的模型绑定问题
- android - 想要删除firebase(Android)中实时数据库的多个(超过1000个节点)节点
- php - 如何仅在服务器端处理中显示某些行?
- java - 错误:包 org.apache.commons 不可访问
- flutter - 颤动如何强制字体大小日期时间选择器颤动?