例如知乎编辑器内,如果粘贴了一段网址,会自动转换为链接。stack上找到的代码不知道该如何用,大家可以看看。functionreplaceURLWithHTMLLinks(text){varexp=/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;returntext.replace(exp,"$1");}是监视keyup来替换的吗?希望得到大家的解答!谢谢!***//Update:2013-12-09:***编辑器为
2 回答
holdtom
TA贡献1805条经验 获得超10个赞
linkify:function(inputText){varreplacedText,replacePattern1,replacePattern2,replacePattern3;varoriginalText=inputText;//URLsstartingwithhttp://,https://,file://orftp://replacePattern1=/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;//URLsstartingwith"www."(without//beforeit,orit'dre-linktheonesdoneabove).replacePattern2=/(^|[^\/f])(www\.[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;//Changeemailaddressestomailto::links.replacePattern3=/(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gi;//Iftherearehrefsintheoriginaltext,let'ssplit//thetextupandonlyworkonthepartsthatdon'thaveurlsyet.varcount=originalText.match(/if(count.length>0){ varcombinedReplacedText;//KeepdelimiterwhensplittingvarsplitInput=originalText.split(/(<\/a>)/g);for(i=0;iif(splitInput[i].match(/ splitInput[i]=splitInput[i].replace(replacePattern1,' $1').replace(replacePattern2,'$1 $2').replace(replacePattern3,' $1'); }}combinedReplacedText=splitInput.join('');returncombinedReplacedText;}else{replacedText=inputText.replace(replacePattern1,'$1'); replacedText=replacedText.replace(replacePattern2,'$1$2'); replacedText=replacedText.replace(replacePattern3,'$1'); returnreplacedText;}},对一段文本,可重复运行。
添加回答
举报
0/150
提交
取消