2014-09-30 127 views
0

我很想檢測一個字符串與正則表達式匹配的位置,但這似乎失敗了模糊。請參閱此plunkrangularjs:正則表達式失敗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

正則表達式的模糊失敗,因爲的lastIndex endsWithPipeOrSpace已更改爲newQueryModified功能。

讀一下RegExp lastIndex屬性。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex

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

當全成匹配發生爲正則表達式,lastIndex的值被改變爲匹配的字符串的長度。
所以在這裏,你必須在lastIndex值到0 endsWithPipeOrSpace重置測試$scope.newquery這樣

$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

非常感謝,良好和簡潔的解釋! – datamosh 2014-09-30 09:22:02