2013-10-23 48 views
0

我幾乎得到了這個工作。我想知道是否有更好的方法很多如何用鏈接替換純文字鏈接,舉例?

Root problem

Fiddle

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); 

有什麼想法?

+0

思想取代了它:_wow看起來messy_。你有任何其他問題嗎? – Halcyon

+2

這會更適合http://codereview.stackexchange.com/ – ediblecode

+0

取代'innerHTML'會很危險。嘗試遍歷樹並僅替換每個元素的'innerText'。 – Mohsen

回答

3

在在CodeReview這個問題是相當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重」 的 「@」 符號的錯誤 - 我只是@@

+0

你現在有> 10代表... – Shog9

0

想這問題已經回答here

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

這產生了不同的令人無法接受的結果。例如: –

+0

[小提琴](http://jsfiddle.net/bPtaA/) –

+0

好的。提供鏈接,因爲它得分高。沒有測試它,只是希望你可以使用它... –