我几乎已经完成了这项工作。我想知道是否有更好的方法。
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);
有什么想法吗?