首页 > 解决方案 > 检测到以 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>

标签: javascriptjqueryhref

解决方案


如果有人需要,我根据@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>


推荐阅读