2012-08-08 3 views
4

어떤 텍스트가있는 URL을 래핑하고 하이퍼 링크로 바꿀려고하는데 이미 하이퍼 링크로 싸여있는 URL을 감싸고 싶지 않습니다. 예를 들어Regex URL과 일치하는 하이퍼 링크를

:

<a href="http://twitter.com">Go To Twitter</a> 
here is a url http://anotherurl.com 

다음 코드 :

<a href="<a href='http://twitter.com/twitter'>http://twitter.com/twitter</a>">@BIR</a> 
<a href="http://anotherurl.com">http://anotherurl.com</a> 

어떻게 이미 하이퍼 링크 URL을 제외 할 수있는 정규식을 수정할 수 있습니다

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

다음과 같은 출력을 제공합니다?

감사

답변 :

새로운 방법은 다음과 같습니다 필요한

function replaceURLWithHTMLLinks(text) { 
    var exp = /(?:^|[^"'])((ftp|http|https|file):\/\/[\S]+(\b|$))/gi 
    return text.replace(exp, " <a href='$1'>$1</a>"); 
} 

위의 코드의 함수로. 코멘트에있는 링크에서 정규식을 수정했는데, 여기에는 전체 중지가 포함될 버그가 포함되어 있기 때문에 전체 URL 뒤에 오는 전체 중지를 제외합니다.

+1

html을 구문 분석하기 위해 정규식을 사용하지 마십시오. http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags –

+1

[이 질문에 유사] (http://stackoverflow.com/q/2177142/615754)). 그리고 [이 다른 질문] (http://stackoverflow.com/questions/8038910/regex-to-find-urls-not-in-tags?rq=1). 또는 [이 하나] (http://stackoverflow.com/q/2641582/615754). – nnnnnn

+0

우수! 감사합니다 nnnnnn. 나는 오늘 아침에 검색을했지만 분명히 내 검색 문구가 유용한 것과 일치하지 않았다. 공유해 주셔서 감사합니다! – Base33

답변

2

javascript doesn't seem to support negative look-behind부터 바꾸기 기능을 사용하여 속임수를 쓰셔야합니다. href (어쩌면 당신도 또한 src을 고려해야한다) 캡처 :

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

demo

편집

만 실제 텍스트 노드의 링크를 대체 할 "더 나은"버전을 참조하십시오 :

function repl(node) { 
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i; 
    var nodes=node.childNodes; 
    for (var i=0, m=nodes.length; i<m; i++){ 
    var n=nodes[i]; 
    if (n.nodeType==n.TEXT_NODE) { 
     var g=n.textContent.match(exp); 
     while(g) { 
     var idx=n.textContent.indexOf(g[0]); 
     var pre=n.textContent.substring(0,idx); 
     var t=document.createTextNode(pre); 
     var a=document.createElement("a"); 
     a.href=g[0]; 
     a.innerText=g[0]; 
     n.textContent = n.textContent.substring(idx+g[0].length); 
     n.parentElement.insertBefore(t,n); 
     n.parentElement.insertBefore(a,n); 
     g=n.textContent.match(exp); 
     } 
    } 
    else { 
     repl(n); 
    } 
    } 
} 

var r=repl(document.getElementById("t")) 

demo

+0

진짜 좋은 대답. 나는 다른 기능을 찾았지만 위대한 대답을 위해 – Base33

관련 문제