Skip to content
Advertisement

How to remove space followed by a comma in comma separated array in Angular Split method?

I have a comma separated string value. And using split() method, I’m converting it to a array. But in some cases if user put space after a comma, it will create an extra space between word.

Please refer to the code and the image .

.html

<form [formGroup]="myForm">

<input type="text" class="form-control" formControlName="title">
<button (click)="addTitle(myForm.value)">Save</button>

</form>

.ts

public title = " ";

public myForm: FormGroup = new FormGroup({
    title: new FormControl('', Validators.required)
  });

  addTitle(value: any){
    this.title = value.title;
    const array = this.title.split(',');
    console.log('array',array);
  }

enter image description here

Advertisement

Answer

You could do something like the following:

addTitle(value: any){
    this.title = value.title;

    // here the trim() function will remove he white space from each element
    const array = this.title.split(',').map(s => s.trim());
    console.log('array',array);
  }
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement