serg kalinin
serg kalinin

Reputation: 13

How to trim spaces dynamically?

I use input component from material library. User inputs to fileld several spaces + several symbols + several spaces. After that he click on submit button. In result, console displays only symbols (without begin/end spaces). Its OK, its right behavior.

But i need begin/end spaces disappeared after user press key up. Help me do it.

LIVE DEMO

<md-input-container>
  <label>Title</label>
  <input ng-model="$ctrl.pass">
</md-input-container>
<button ng-click="$ctrl.change()">submit</button>

class HomeCtrl {
  constructor() {
    this.pass = null;
    this.change = function() {
      setTimeout(_ => {
        console.log(this.pass, 'length:', this.pass.length)
      });
    }
  }
}

Upvotes: 0

Views: 278

Answers (1)

Vishal Viswanathan
Vishal Viswanathan

Reputation: 11

Add ng-trim='false' to input element (default will be true) so that AngularJS will not automatically trim the input. <input ng-model="$ctrl.pass" ng-trim="false">

Update this.pass in the change() function as follows:

this.pass = this.pass.replace(/\s+/g, ''); //to remove all whitespaces
this.pass = this.pass.trim(); //to remove leading and trailing whitespaces

this.change = function() {
      this.pass = this.pass.replace(/\s+/g, '');
      setTimeout(_ => {
        console.log(this.pass, 'length:', this.pass.length)
      });
}

References:

Upvotes: 1

Related Questions