鍍金池/ 問答/Java  HTML/ 如何使用js將文本中的url轉(zhuǎn)化為可點(diǎn)擊的link?

如何使用js將文本中的url轉(zhuǎn)化為可點(diǎn)擊的link?

    function replaceURLToLink(text) {
     const reg = /((http|https):\/\/[\w.\/]+)(?![^<]+>)/gi
     return text.replace(reg,"<a href='$1' target='_blank'>$1</a>")
    }
    // 目前這個(gè)只能匹配到http(s)://www.baidu.com,對(duì)于http://baidu.com/index/search?keyword=123這種格式的如何優(yōu)化?
回答
編輯回答
影魅
<style>
    a{color:red;}
</style>

<h1>這是鏈接:http://www.baidu.com。測(cè)試</h1>

<script>
    var h1 = document.getElementsByTagName('h1')[0];
    h1.innerHTML = h1.innerHTML.replace(/((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)/g, '<a href="$1" >$1</a>');
</script>
2018年1月23日 08:32