How to replace plain URLs with links, with example?
本问题已经有最佳答案,请猛点这里访问。
我差点儿把它弄好了。我想知道有没有更好的方法。
根问题
小提琴
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function replaceURLWithHTMLLinks(text) { text = text.replace(/a/g,"--ucsps--"); text = text.replace(/b/g,"--uspds--"); var arrRegex = [ /(\([^)]*\b)((?:https?|ftp|file):\/\/[-A-Za-z0-9+&@#\/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#\/%=~_()|])(\))/ig, /(\([^)]*\b)((?:https?|ftp|file):\/\/[-A-Za-z0-9+&@#\/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#\/%=~_()|])(.?\b)/ig, /()(\b(?:https?|ftp|file):\/\/[-a-z0-9+&@#\/%?=~_()|!:,.;]*[-a-z0-9+&@#\/%=~_()|])(.?\b)/ig]; for (i = 0; i < arrRegex.length; i++) { text = text.replace(arrRegex[i],"$1a$2b$3"); } text = text.replace(/a([^b]*)b/g,"$1"); text = text.replace(/--ucsps--/g,"a"); text = text.replace(/--uspds--/g,"b"); return text; } var elm = document.getElementById('trythis'); elm.innerHTML = replaceURLWithHTMLLinks(elm.innerHTML); |
有什么想法吗?
在代码审查中,这个问题得到了很好的回答。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | function replaceURLWithHTMLLinks(text) { var re = /(\(.*?)?\b((?:https?|ftp|file):\/\/[-a-z0-9+&@#\/%?=~_()|!:,.;]*[-a-z0-9+&@#\/%=~_()|])/ig; return text.replace(re, function(match, lParens, url) { var rParens = ''; lParens = lParens || ''; // Try to strip the same number of right parens from url // as there are left parens. Here, lParenCounter must be // a RegExp object. You cannot use a literal // while (/\(/g.exec(lParens)) { ... } // because an object is needed to store the lastIndex state. var lParenCounter = /\(/g; while (lParenCounter.exec(lParens)) { var m; // We want m[1] to be greedy, unless a period precedes the // right parenthesis. These tests cannot be simplified as // /(.*)(\.?\).*)/.exec(url) // because if (.*) is greedy then \.? never gets a chance. if (m = /(.*)(\.\).*)/.exec(url) || /(.*)(\).*)/.exec(url)) { url = m[1]; rParens = m[2] + rParens; } } return lParens +"" + url +"" + rParens; }); } |
注意:我在"var re"中的"@"符号有错误-我刚用替换它@@
我猜这个问题已经在这里回答了
1 2 3 4 | function replaceURLWithHTMLLinks(text) { var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; return text.replace(exp,"$1"); } |