Adding Whitespace to a String in Typescript (In Angular)

Adding transformations to String using Angular 2

You can use custom pipe like this:

@Pipe({name: 'whitespace'})
export class WhiteSpacePipe implements PipeTransform {
transform(value: number) {
return value.replace(/([A-Z])/g, ' $1');
}
}

And in your template:

{{ str | whitespace }}

If you want to avoid first whitespace then:

value.replace(/([A-Z])/g, ' $1').trim()

See also http://plnkr.co/edit/VnWHrI6aoTuooqFgj2Qa?p=preview

Angular typescript - how to remove space in between words in component.html

Since @Andrei Tatar didn't post an answer with an example on how it can be done with a pipe, I put this together to show how easy it is to manipulate data with pipes.

@Pipe({
name: "trimWhitespace"
})
export class TrimWhitespacePipe implements PipeTransform {
transform(value: string): string {
return value.replace(/\s/g,'')
}
}

and use it with <img [src]="item.name | trimWhitespace"

Adding a space before 3rd character from end of string

Use String#replace method and replace last 3 characters with leading space or assert the position using positive look-ahead assertion and replace with a white space.

string = string.replace(/.{3}$/,' $&');
// or using positive look ahead assertion
string = string.replace(/(?=.{3}$)/,' ');

console.log(  'A123A123'.replace(/.{3}$/, ' $&'), '\n',  'A13A123'.replace(/.{3}$/, ' $&'), '\n',  'A1A123'.replace(/.{3}$/, ' $&'), '\n',  'AA123'.replace(/.{3}$/, ' $&'), '\n',  'A123'.replace(/.{3}$/, ' $&'), '\n',  'A123'.replace(/(?=.{3}$)/, ' '))

How to remove whitespace from a string in typescript?

Problem

The trim() method removes whitespace from both sides of a string.

Source

Solution

You can use a Javascript replace method to remove white space like

"hello world".replace(/\s/g, "");
Example