【问题标题】:angularjs: regexp fails onblurangularjs:正则表达式失败 onblur
【发布时间】:2014-09-30 08:03:22
【问题描述】:

我很想检测字符串与正则表达式匹配的位置,但这似乎在模糊时失败。请看这个plunkr

这是 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-trim="false"

 <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()">

【问题讨论】:

    标签: regex angularjs input trim onblur


    【解决方案1】:

    正则表达式在模糊时失败,因为 endsWithPipeOrSpace 的 lastIndex 已在 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";
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-24
      • 2019-11-09
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 2021-05-18
      相关资源
      最近更新 更多