猿问

如何用链接替换普通URL?

如何用链接替换普通URL?

我使用下面的函数来匹配给定文本中的URL,并将它们替换为HTML链接。正则表达式工作得很好,但目前我只替换第一场比赛。

我怎样才能替换所有的URL?我想我应该用主管但我真的不知道该怎么做。

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
    return text.replace(exp,"<a href='$1'>$1</a>"); }


拉丁的传说
浏览 1523回答 4
4回答

精慕HU

我对Travis的代码做了一些小小的修改(只是为了避免任何不必要的重声明-但它对我的需求非常有用,所以工作非常好!):function&nbsp;linkify(inputText)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;replacedText,&nbsp;replacePattern1,&nbsp;replacePattern2,&nbsp;replacePattern3; &nbsp;&nbsp;&nbsp;&nbsp;//URLs&nbsp;starting&nbsp;with&nbsp;http://,&nbsp;https://,&nbsp;or&nbsp;ftp:// &nbsp;&nbsp;&nbsp;&nbsp;replacePattern1&nbsp;=&nbsp;/(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim; &nbsp;&nbsp;&nbsp;&nbsp;replacedText&nbsp;=&nbsp;inputText.replace(replacePattern1,&nbsp;'<a&nbsp;href="$1"&nbsp;target="_blank">$1</a>'); &nbsp;&nbsp;&nbsp;&nbsp;//URLs&nbsp;starting&nbsp;with&nbsp;"www."&nbsp;(without&nbsp;//&nbsp;before&nbsp;it,&nbsp;or&nbsp;it'd&nbsp;re-link&nbsp;the&nbsp;ones&nbsp;done&nbsp;above). &nbsp;&nbsp;&nbsp;&nbsp;replacePattern2&nbsp;=&nbsp;/(^|[^\/])(www\.[\S]+(\b|$))/gim; &nbsp;&nbsp;&nbsp;&nbsp;replacedText&nbsp;=&nbsp;replacedText.replace(replacePattern2,&nbsp;'$1<a&nbsp;href="http://$2"&nbsp;target="_blank">$2</a>'); &nbsp;&nbsp;&nbsp;&nbsp;//Change&nbsp;email&nbsp;addresses&nbsp;to&nbsp;mailto::&nbsp;links. &nbsp;&nbsp;&nbsp;&nbsp;replacePattern3&nbsp;=&nbsp;/(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim; &nbsp;&nbsp;&nbsp;&nbsp;replacedText&nbsp;=&nbsp;replacedText.replace(replacePattern3,&nbsp;'<a&nbsp;href="mailto:$1">$1</a>'); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;replacedText;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答