首页 > 解决方案 > 如何在字符串中查找所有 url 时停止显示 mailto

问题描述

我正在尝试从使用以下代码的字符串中查找所有 URL。

Urlify :function (text) {
        var urlRegex = /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g;
    }

它工作正常,但是当涉及到电子邮件 ID 时,它也会显示mailto。我不想显示。

< abc@test.com<mailto:abc@test.com>>

任何人都可以帮助我避免将Mailto与电子邮件 ID 一起显示。

谢谢。

标签: javascripthtmlcssregex

解决方案


更新的代码/脚本
我认为这就是你要找的

但最初我会从这个正则表达式部分删除冒号[-a-zA-Z0-9@%._\+~#=]

(除了后面的第一个冒号(http(s)?:\/\/)

document.getElementById("doIt").addEventListener("click", function(){
  var urlRegex = /(http(?:s)?:\/\/)?(www\.)?([-a-zA-Z0-9@%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&\/=]*))/g;

  document.getElementById("result").innerHTML = document.getElementById("links").value.replace(urlRegex,
    function (url) {
      var extraText = /@/gi.test(url) ? "mailto:":"";
      return '<a href="' +extraText+ url + '" title="'+ url +'">' + url + '</a>';
    });
   });
<textarea id="links" rows="4" cols="50">
Billions of people abc@gmail.com around the world are still https://www.wikipedia.org/ without internet access. Loon is a network of balloons traveling on the edge of space, delivering connectivity to people in unserved and underserved communities around the world.
</textarea>
<br />
<button id="doIt"> replace </button>
<br />
<div id="result">
</div>

更新更改除“电子邮件地址:”以外的所有链接

    document.getElementById("doIt").addEventListener("click", function(){
      var urlRegex = /(http(?:s)?:\/\/)?(www\.)?([-a-zA-Z0-9@%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&\/=]*))/g;

      document.getElementById("result").innerHTML = document.getElementById("links").value.replace(urlRegex,
        function (url) {
          //Check if url is an email (this regex could be improved) 
          return (/.+@.+/gi.test(url))? url :'<a href="' + url + '" title="'+ url +'">' + url + '</a>';
        });
       });
    <textarea id="links" rows="4" cols="50">
      Billions of people abc@gmail.com around the world are still https://www.wikipedia.org/ without internet access. Loon is a network of balloons traveling on the edge of space, delivering connectivity to people in unserved and underserved communities around the world.
    </textarea>
    <br />
    <button id="doIt"> replace </button>
    <br />
    <div id="result">
    </div>


推荐阅读