2014-04-22 7 views
0

빠른 질문 - 왜이 기능이 작동하지 않습니까?자바 스크립트는 이메일 주소를 바꿉니다

나는 모든 것을 쓸모없는 것으로 테스트했다. 기본적으로 mailto 링크를 추가 할 수있는 이메일에 링크를 추가하려고합니다.

전자 메일 링크를 mailto 태그로 대체하지 않습니다.

감사합니다, 해리는

$(document).ready(function() { 
    var email_regex = /([a-zA-Z0-9._-][email protected][a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi; 

    var bodyText = $('body').html(); 
    var match = email_regex.exec(bodyText); 
    // To do - Don't try it when there is already a mailto link, can probably just add mailto to the regex. 
    for (var i = 0; i < match.length; i++) { 
     bodyText.replace(match[i], '<a href="mailto:' + match[i] + '">' + match[i] + '</a>'); 
     console.log(match[i]); 
    } 
    $('body').html(bodyText); 
    console.dir(match); 
}); 
+1

작동하지 않습니다? – A1rPun

+0

OP를 업데이트했습니다. 이메일 링크를 mailto 태그로 대체하지 않습니다. –

답변

6

당신은 대신에 나는 가정한다 :

var result = bodyText.replace(email_regex,'<a href="mailto:$1">$1</a>'); 
console.log(result); // This two lines are enough. 

전체 코드 :

g 플래그는하지 않습니다
$(document).ready(function() { 
    var email_regex = /([a-zA-Z0-9._-][email protected][a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi; 
    var bodyText = $('body').html(); 
    var result = bodyText.replace(email_regex,'<a href="mailto:$1">$1</a>'); 
    console.log(result); // This two lines are enough. 
}); 
+0

이 작품! 감사! –

+0

도움이 된 것을 기쁘게 생각합니다.) –

+0

+1 기술적으로 말하자면,이 질문에 대답하지 않는 이유는 무엇입니까 * –

1

첫 번째 문제가 있음 한 번에 모든 경기를 검색하십시오. 루프에서 exec()으로 전화를 걸기 만하면됩니다. 당신은해야 할 것 :

var match; 
while ((match = email_regex.exec(bodyText)) !==null) { 
} 

두 번째 문제는 replace() 원래 문자열을 수정하지 않습니다. 당신은 필요합니다 :

bodyText= bodyText.replace(match[i], '<a href="mailto:' + match[i] + '">' + match[i] + '</a>'); 

아직도, 당신은 쉽게 이런 식으로 무한 루프에 들어갈 수 있습니다. 당신은 복사 작업을 할 거라고 :

var newBodyText = bodyText; 
... 
while ((match = email_regex.exec(bodyText)) !==null) { 
    ... 
    newBodyText = newBodyText.replace(...) 
} 
$('body').html(newBodyText); 

참조 : 이봐, 해리, 무슨