如何用链接替换普通 URL,例如? [英] How to replace plain URLs with links, with example?
本文介绍了如何用链接替换普通 URL,例如?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我快要完成这项工作了.我想知道是否有 更好的方法.
I've nearly got this working. I wanted to know if there was a much better way.
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, "<a href='$1'>$1</a>");
text = text.replace(/--ucsps--/g, "a");
text = text.replace(/--uspds--/g, "b");
return text;
}
var elm = document.getElementById('trythis');
elm.innerHTML = replaceURLWithHTMLLinks(elm.innerHTML);
有什么想法吗?
推荐答案
在 CodeReview 上回答了这个问题非常非常好.
Over at CodeReview this question was answered quite splendidly.
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 + "<a href='" + url + "'>" + url + "</a>" + rParens;
});
}
注意:我在var re"中的@"符号有错误 - 我只是用@@替换了它
Note: I had errors with the "@" symbol in the "var re" - I just replaced it with @@
这篇关于如何用链接替换普通 URL,例如?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文