soja4
soja4

Reputation: 41

angularjs - trim() function is not working

This is my js code that deletes multiple spaces in string and trim string:

$scope.fixInput = function (input){
    input = input.replace(/\s+/g, ' ').trim();
    return input;
};

And i have input field in html:

<input type="text" ng-model="userName" ng-change="userName=fixInput(userName)"/>

And there is a strange behaviour. When i type for example

"    a    a       a   "

the result will be fine

"a a a"

but when i type

"       aaa        " 

when it has to just to trim string the result is not changing, it's the same.

Upvotes: 0

Views: 3970

Answers (1)

sp00m
sp00m

Reputation: 48807

Angular automatically trims input[text]. If you want to do it manually, you have to disable it:

<input type="text" ng-model="userName" ng-trim="false" ng-change="userName=fixInput(userName)" />
                                       ^^^^^^^^^^^^^^^

From https://docs.angularjs.org/api/ng/input/input%5Btext%5D:

If set to false AngularJS will not automatically trim the input. This parameter is ignored for input[type=password] controls, which will never trim the input.

(default: true)

Upvotes: 1

Related Questions