如何使用js将文本中的url转化为可点击的link?

    function replaceURLToLink(text) {
     const reg = /((http|https):\/\/[\w.\/]+)(?![^<]+>)/gi
     return text.replace(reg,"<a href='$1' target='_blank'>$1</a>")
    }
    // 目前这个只能匹配到http(s)://www.baidu.com,对于http://baidu.com/index/search?keyword=123这种格式的如何优化?
阅读 2.2k
1 个回答
<style>
    a{color:red;}
</style>

<h1>这是链接:http://www.baidu.com。测试</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>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题