如何在Angular中计算长度时排除空格?

时间:2017-01-20 12:09:28

标签: angularjs

我正在检查标题的长度并根据该长度设置一个类。我注意到,长度也在检查空格,所以当你有一个空格时,它会算作+1。

我想摆脱它。所以我想排除长度中的空格数。如果可能的话,我该怎么办呢?

<h1 ng-class="{'specific-class': title.name.length >= 10}">{{title.name}}</h1>

3 个答案:

答案 0 :(得分:1)

您可以通过用空字符串替换空格来检查:

title.name.replace(' ','').length >= 10

完整的一行是:

<h1 ng-class="{'specific-class': title.name.replace(' ','').length >= 10}">{{title.name}}</h1>

假设title.name'Hello World!'title.name.length为12,title.name.replace(' ','').length为11。

修改

事实证明,你不能在HTML中使用斜杠,否则Angular会将它们转换为html安全字符。因此,我建议将检查器分成自己的模块。我已附上一个片段,以便您了解它是如何完成的:

angular
  .module("app", [])
  .controller("test", function($scope) {
    // Example title object. Just load title objects as you would normally.
    $scope.title = {name: 'The World of McNamara'};

    // The actual magic happens here:
    $scope.checker = function(word) {
      return word.replace(/\s/g, '').length >= 10;
    }
  })
.specific-class {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<!-- snippet checks whatever is passed to it as title.name -->
<div ng-app="app" ng-controller="test">
  <h1 ng-class="{'specific-class': checker(title.name)}">{{title.name}}</h1>
</div>

答案 1 :(得分:0)

你必须使用.trim:

title.name.trim().length

或者你可以这样做:

title.name.replace(" ", "").length

编辑:

在你的代码中就是这样:

<h1 ng-class="{'specific-class': title.name.replace(' ', '').length >= 10}">{{title.name}}</h1>

使用三元逻辑:

<h1 ng-class="(title.name.replace(' ', '').length >= 10)? 'specific-class' : 'another-class' ">{{title.name}}</h1>

答案 2 :(得分:0)

您可以通过多种方式从字符串中删除空格,就像使用split然后连接一样。

title.name.split(' ').join('')

或者可以通过正则表达式方法完成:

title.name.replace(/ /g, '')

由您决定如何实施。