0

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.

5
  • 1
    Changing model on model change, can't this be dangerous (e.g. infinitely looping)? Commented Mar 21, 2017 at 15:11
  • I have just use this code snippet at browser console var v= " aaa "; v.replace(/\s+/g, ' ').trim(); and found the output as aaa. So is it fine or you are expecting something else? Commented Mar 21, 2017 at 15:24
  • @AbhisekMalakar I also saw that and it confuses me. But the value in input is not changing. Commented Mar 21, 2017 at 15:30
  • I just tried it in angular context and found an error, the input.replace is not a function Commented Mar 21, 2017 at 15:52
  • sorry, my bad. It gives me expected resultvar app = angular.module("test",[]) .controller("TestController", function($http,$scope){ var vm = this; vm.my = true; $scope.fixInput = function (input){ console.log(input); input = input.replace(/\s+/g, ' ').trim(); return input; }; }); Commented Mar 21, 2017 at 16:04

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

i tried with that and i removed trim function and now i'm getting what i want, i just have one space at the begining and at the end that i have to trim

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.