javascript - Get url from string using regex
phpcn_u1582
phpcn_u1582 2017-05-19 10:13:12
0
2
449
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_u1582
phpcn_u1582

reply all(2)
洪涛

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);
漂亮男人
/(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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template