【问题标题】:Detected link problem staring with www., replace with a element检测到以 www. 开头的链接问题,用一个元素替换
【发布时间】:2020-07-04 05:54:21
【问题描述】:

当我匹配 httphttps 时,我可以将其转换为 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>

【问题讨论】:

  • www 不是协议,除非链接与您的域相关,否则不会在没有协议(http:// 或 https:// 等)的情况下打开其他站点
  • @charlietfl 哦,我现在明白了,是的,whiteout 协议不起作用。不敢相信我以前没有注意到这一点。但我猜我可以附加它。
  • 很容易错过这样的事情......不像我从来没有链接到abc.com/xyx.com。 url 的用户输入通常需要双重检查协议例如存在

标签: javascript jquery href


【解决方案1】:

基于@charlietfl cmets,如果有人需要,我会为自己写这个(我认为它涵盖了大多数情况):

$("[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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多