I'm displaying array keys in header of a table and I have underscore in my keys. I want to replace underscore with space in html table. I do not want to do it in component as I have other requirements.
<table>
   <thead>
       <tr>
           <th *ngFor="let header of printFields">{{header}}</th>
       </tr>
   </thead>
   <tbody>
       <tr *ngFor="let ab of printData">
           <td *ngIf="ab.Bill_Number">{{ab.Bill_Number}}</td>
           <td>.....</td>
           <td>.....</td>
       </tr>     
   </tbody>
</table>
                Use the String. replaceAll method to replace all spaces with underscores in a JavaScript string, e.g. string. replaceAll(' ', '_') . The replaceAll method returns a new string with all whitespace characters replaced by underscores.
To replace underscores with spaces in Python: Use the str. split() method to split the string on each underscore. Call the join() method on a string containing a space. The join method will join the words with a space separator.
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 :-)
this case angular 6:
 underscore(selectkpi){
    this.selectedUnderKpi = selectkpi.replace(' ', '_');
    var a = this.selectedUnderKpi.
    console.log("ini = ",a);
  }
                        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
You can do the following :
in the transform method write the following
transform(value: any, args?: any): string {
    let [first, ...rest] = value.split("_");
    if (rest.length === 0) return first;
    else return `${first} ${rest.join(" ")}`;
}
this code will handle if the key have underscore or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With