2012-01-09 4 views
2

함수에 문자열의 접미사를 확인 -내가이 endsWith 기능 다운로드

String.prototype.endsWith = function(suffix) { 
    return this.match(suffix+"$") == suffix; 
} 

을 내가 보여 jQuery를 사용하고

function validator(form){ 
    var input = form.user.value; 

    if(input.endsWith("vdr")) { 
     if(input != ""){ 
      $('#userb').fadeOut("fast"); 
      $('#userk').fadeIn("fast"); 
     } 
    }else{ 
     $('#userk').fadeOut("fast"); 
     $('#userb').fadeIn("fast"); 
    } 
} 

으로 양식 입력을 확인하기 위해 사용하는 것을 시도하고있다 div. 문제는 아무것도하지 않는다는 것이고 endsWith()에 대한 검사없이 작동하기 때문에 아마도 문제를 일으키는 함수 일 것입니다. 왜 이것이 작동하지 않습니까? 거기에 어떤 대안이 있습니까 그게 효과가 있을까요?

답변

1

String.match는 경기의 배열을 반환합니다. 그래서 RegExp.test 더 적용, 당신은 단지 조건을 테스트하고

String.prototype.endsWith = function(suffix) { 
    return this.match(suffix+"$")[0] === suffix; 
} 
2

.match은 일치하는지 여부에 따라/undefined 배열을 반환합니다. 단순히 부울로 변환 :

String.prototype.endsWith = function(suffix) { 
    return !!this.match(suffix+"$"); 
} 

여기 데모입니다 : http://jsfiddle.net/KcvMZ/

2

: 이런 식으로 뭔가를 시도하십시오. 그래서 ...

String.prototype.endsWith = function(suffix) { 
    return RegExp(suffix+"$").test(this); 
} 

... 작동해야합니다.

alert("100$".endsWith("$")) // surprise 

비 정규 표현식 코드가 어쩌면 더 빠르고 정확 것이다 : 그들은 계정에 특수 문자를하지 않기 때문에

1

정규 표현식 기반 구현은 결함이

String.prototype.endsWith = function(suffix) { 
    var n = this.lastIndexOf(suffix); 
    return n >= 0 && n == this.length - suffix.toString().length 
} 
관련 문제