2014-09-30 3 views
0

문자열이 정규 표현식과 일치하는 곳을 감지하고 싶지만 이것이 흐리게 처리되지 않는 것 같습니다. 이 plunkr을 참조하십시오. 여기 angularjs : regexp가 onblur에 실패했습니다

은 JS의 :

var endsWithPipeOrSpace = /\s+$|\|$/g; 

$scope.inputGetFocus = function() { 
    $scope.msg = "input gained focus" 
    if (endsWithPipeOrSpace.test($scope.newquery)) { 
    $scope.msg += " string match"; 
    } else { 
    $scope.msg += " string doesn't match"; 
    } 
} 

$scope.inputLostFocus = function() { 
    $scope.msg = "input has lost focus" 
    if (endsWithPipeOrSpace.test($scope.newquery)) { 
    $scope.msg += " string match"; 
    } else { 
    $scope.msg += " string doesn't match"; 
    } 
} 


$scope.newQueryModified = function() { 
    $scope.msg = "input modified" 
    if (endsWithPipeOrSpace.test($scope.newquery)) { 
    $scope.msg += " string match"; 
    } else { 
    $scope.msg += " string doesn't match"; 
    } 
} 

여기에 HTML의 :
나는 NG-트림

<input type="text" class="form-control" 
id="newquery" ng-model="newquery" 
placeholder="Enter your query" 
autofocus required autocomplete="off" 
ng-change="newQueryModified()" 
ng-trim="false" 
ng-focus="inputGetFocus()" 
ng-blur="inputLostFocus()"> 

답변

0

정규 표현식은 흐림 실패 = "false"를 선언하고있어주의의는 lastIndex 때문에 endsWithPipeOrSpace이 (가) newQueryModified 기능에서 변경되었습니다.

RegExp lastIndex 속성에 대한 정보 읽기.

The lastIndex is a read/write integer property of regular expressions that specifies the index at which to start the next match.

성공적인 경기는 정규 표현식 발생 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex


는 lastIndex 속성 값은 일치하는 문자열의 길이로 변경됩니다.
그래서 여기이

$scope.inputLostFocus = function() { 
    $scope.msg = "input has lost focus" 
    endsWithPipeOrSpace.lastIndex = 0;   // reset lastIndex here 
    if (endsWithPipeOrSpace.test($scope.newquery)) { 
     $scope.msg += " string match"; 
    } else { 
     $scope.msg += " string doesn't match"; 
    } 
} 
+0

감사처럼 endsWithPipeOrSpace와 시험 $scope.newquery에 0으로 lastIndex 값을 재설정해야 할 많은 좋은 간결한 설명! – datamosh