어떤 텍스트가있는 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 뒤에 오는 전체 중지를 제외합니다.
html을 구문 분석하기 위해 정규식을 사용하지 마십시오. http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags –
[이 질문에 유사] (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
우수! 감사합니다 nnnnnn. 나는 오늘 아침에 검색을했지만 분명히 내 검색 문구가 유용한 것과 일치하지 않았다. 공유해 주셔서 감사합니다! – Base33