Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - "length" method not counting space character at the end of a string

Tags:

angularjs

I was trying to count the length of a string($scope.count = $scope.str.lenght). But, when there is a space at the end of the string its not being counted until there is a character after the space.
Example:

"Hello " = 5,  
"Hello u" = 7  

Any idea why is it designed in this way?
How can I count the space at the end of the string?

like image 284
Layeek Avatar asked Nov 30 '25 14:11

Layeek


1 Answers

By default Angular will trim the trailing spaces on ngModel. To override this behaviour add:

ng-trim="false"

more info

(function() {
	'use strict';
  
  angular.module('myApp', []);
  
  angular.module('myApp').controller('MyController', MyController);
  
  MyController.$inject = [];
  function MyController() {
    var main = this;
    main.someText = 'abcde';

  }
  
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
  <div ng-controller="MyController as main">
    <input type="text" ng-model="main.someText" ng-trim="false">
    {{main.someText.length}}
  </div>
</body>
like image 73
Giovani Vercauteren Avatar answered Dec 02 '25 04:12

Giovani Vercauteren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!