鍍金池/ 問(wèn)答/HTML/ js如何自動(dòng)識(shí)別內(nèi)容中的Url并添加超鏈接

js如何自動(dòng)識(shí)別內(nèi)容中的Url并添加超鏈接

比如在一個(gè)聊天中,對(duì)方發(fā)的文字中包含一個(gè)地址 ,那么就直接顯示為超鏈接的形式
超鏈接有可能帶http,有可能不帶
比如
https://baidu.com
http://baidu.com
www.baidu.com
這個(gè)正則不能識(shí)別www開(kāi)頭的呀,只能識(shí)別http開(kāi)頭的
<div id="text">
www.baidu.com
</div>
<script type="text/javascript">
var txt = document.getElementById('text').innerHTML;
var regexp = /(http://|https://)((w|=|?|.|/|&|-)+)/g; //正則匹配
txt1=txt.replace(regexp,function($url){

return "<a href='" + $url + "' target='_blank'>" + $url + "</a>";

});
document.getElementById('text').innerHTML=txt1
//alert(txt.replace(regexp,"m"));
//alert(txt);
</script>

回答
編輯回答
維她命

js正則
let expr = /<a1+?href=["']?(2+)["']?1*>(3+)</a>/mg


  1. > ?
  2. "' ?
  3. < ?
2017年5月22日 13:15