search

Home  >  Q&A  >  body text

javascript - Get url from string using regex

let str = "aaaa.com bbbb.com";
let re = /(http:\/\/)?([A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*)/g;
str = str.replace(re,function(a,b,c){return `<a href="http://${c}" target="_blank">${a}</a>`;});
console.log(str);

This regular rule is relatively easy to use. The only problem is that if there are spaces in the string, it cannot be divided into two URLs.
Solution

phpcn_u1582phpcn_u15822829 days ago467

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-05-19 10:15:12

    There is a problem with your regular expression, please modify it as follows:

    var str = "aaaa.com bbbb.com http://www.yugasun.com";
    var re = /([a-zA-z]+:\/\/)?(([^\s]+)\.([^\s]+))/g;
    str = str.replace(re,function(a,b,c){return `<a href="http://${c}" target="_blank">${a}</a>`;});
    console.log(str);

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-19 10:15:12

    /(http:\/\/)?[A-Za-z0-9]*\.[A-Za-z0-9]+\.(:?com|cn|org|net|biz|...还有一大堆...)/g

    Speaking of which, it is really difficult to accurately judge the domain name that is not fully written. You can enumerate all the domain name suffixes, but there is still an error. Try this method I wrote. This regular expression is wrong. Try writing it according to my writing method.

    reply
    0
  • Cancelreply