How to replace underscore(_) with space (' ') in angular view?
You can use a pipe
https://angular.io/guide/pipes
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replaceUnderscore'})
export class ReplaceUnderscorePipe implements PipeTransform {
transform(value: string): string {
return value? value.replace(/_/g, " ") : value;
}
}
Then use it like
{{ header|replaceUnderscore}}
You could also make a more generic version that takes the pattern to replace and the replacement as parameters, like @Ash-b's answer for angularJs
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
transform(value: string, strToReplace: string, replacementStr: string): string {
if(!value || ! strToReplace || ! replacementStr)
{
return value;
}
return value.replace(new RegExp(strToReplace, 'g'), replacementStr);
}
}
And use it like
{{ header| replace : '_' : ' ' }}
Here is a demo on stackblitz
If there is only one instance you can use this,
{{ header.replace('_', ' ') }}
or else you have to use filter
App.filter('strReplace', function () {
return function (input, from, to) {
input = input || '';
from = from || '';
to = to || '';
return input.replace(new RegExp(from, 'g'), to);
};
});
and use it like
{{ header | strReplace:'_':' ' }}
hope this helps :-)