2009-05-12 4 views
0

나는 HTML의 키워드를 링크로 대체하는 함수를 작성한다. 문제는 키워드가 링크에있을 때 링크가 바뀌게된다는 것입니다. 나는 그것이 교체하기 전에 앵커 태그가 있는지 확인하기 위해 루프의 각 요소를 확인 할jquery and RegExp

<div id="content"> 
    <h2>the word "example" replaced by the link</h2> 
    <p>this is an example</p> 

    <p>this is an example number 2</p> 
    <p><a href="http://www.wrong.com">this is an example</a></p> 
</div> 
+0

jQuery의'.html' 메소드는 모르지만 정규 표현식으로 HTML을 구문 분석하려는 다른 시도처럼 보입니다. – Svante

답변

1

$(document).ready(function() { 
    $("#content").highlight("example", "<a href=\"http://www.example.com\">$1</a>");}); 

jQuery.fn.highlight = function (text, o) { 
return this.each(function(){ 
    var replace = o; 
    $(this).html($(this).html().replace(new RegExp('('+text+'(?![\\w\\s?&.\\/;#~%"=-]*>))', "ig"), replace)); 
});} 

내 HTML.

if(!$(this).is('a')) { 
    // Replace Code here 
} 
+0

나는 루프의 텍스트를 검토하지 않습니다. 교체 기능으로 교체하므로 교체 할 때마다 점검 할 필요가 없습니다. – eyalb