2013-10-23 3 views
0

나는 거의 효과가있다. 이 많이 있는지 알고 싶습니다. 더 좋은 방법입니다.일반 URL을 링크로 바꾸는 방법 (예 :

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

생각으로 대체 : messy_ 보이는 _wow. 다른 질문 있니? – Halcyon

+2

이것은 더 적당 할 것입니다 http://codereview.stackexchange.com/ – ediblecode

+0

대체하는'innerHTML'는 위험 할 것입니다. 트리를 탐색하고 각 요소의 'innerText'만 바꾸십시오. – Mohsen

답변

3

here 대답한다.

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

추측이 질문은 이미이 질문은 매우 splendidly 대답했다 CodeReview에 이상

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

확인. 제공자가 그 점수를 얻었 기 때문에 링크를 제공해야합니다. 그것을 테스트하지 않았습니까, 단지 당신이 그것을 사용할 수 있기를 희망했습니다 ... –

관련 문제