12

How can I trim a text string in my Angular application?

Example

{{ someobject.name }}  

someobject.name results in "name abc"

What I like to achieve is name to be "nameabc" (remove all whitespaces).

I already created a pipe and included this in the typescript file and module)

PIPE:

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({ name: 'trim' })
export class TrimPipe implements PipeTransform {
    transform(value: any) {
        if (!value) {
            return '';
        }

        return value.trim();
    }
}

{{ someobject.name | trim }} still results in "name abc" instead of "nameabc" }}

isherwood
  • 58,414
  • 16
  • 114
  • 157
Babulaas
  • 761
  • 3
  • 13
  • 47

5 Answers5

18

According to the docs, the trim() method removes trailing and leading whitespaces, not those in the middle.

https://www.w3schools.com/Jsref/jsref_trim_string.asp

If you want to remove all whitespaces use the replace function:

"name abc".replace(/\s/g, "");
Jan B.
  • 6,030
  • 5
  • 32
  • 53
3

trim() only removes whitespaces from the start and end of a string:

https://www.w3schools.com/Jsref/jsref_trim_string.asp

have a look here to remove whitespaces between strings:

Replace all whitespace characters

the relevant part is to use it like:

str = str.replace(/\s/g, "X");
tomichel
  • 376
  • 1
  • 4
  • 9
  • Link-only answers are not considered ideal at SO. They can die and rot. Please include the relevant information here, in your post. – isherwood Jul 05 '18 at 20:28
2
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'removeWhiteSpace'
})
export class RemoveWhiteSpacePipe implements PipeTransform {

  transform(value: any): any {
    if (value === undefined)
      return 'undefined';
    return value.replace(/\s/g, "");
  }

}
Nirav
  • 21
  • 1
0

Replace all the whitespace between string

let spaceReg = new RegExp(" ",'g');

let str = "name abc"

str = str.replace(spaceReg,"");

-11

In my case this is bad:

<div>
  {{ someobject.name }}
</div>

Solution:

<div>{{ someobject.name}}</div>

=S

Hector
  • 636
  • 8
  • 16
  • 4
    This doesn't appear to be related to the question. They want to remove whitespace inside a result of a variable, not avoid whitespace around it... – dovetalk Apr 03 '19 at 22:45
  • 2
    This is not a related answer. Understand the question then answer. – Aravindhan R Mar 11 '20 at 06:32