如何在角度视图中用空格('')替换下划线(_)?

Esc*_*sco 1 javascript typescript angular

我在表的标题中显示数组键,并且键中有下划线。我想用HTML表格中的空格替换下划线。我不想在组件中这样做,因为我还有其他要求。

<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>
Run Code Online (Sandbox Code Playgroud)

Ash*_*h-b 6

如果只有一个实例,您可以使用它,

 {{ header.replace('_', ' ') }} 
Run Code Online (Sandbox Code Playgroud)

否则你必须使用过滤器

App.filter('strReplace', function () {
 return function (input, from, to) {
 input = input || '';
 from = from || '';
 to = to || '';
 return input.replace(new RegExp(from, 'g'), to);
 };
});
Run Code Online (Sandbox Code Playgroud)

并像这样使用

 {{ header | strReplace:'_':' ' }}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 :-)


Dav*_*vid 6

你可以用管子

https://angular.io/guide/管道

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

@Pipe({name: 'replaceUnderscore'})
export class ReplaceUnderscorePipe implements PipeTransform {
  transform(value: string): string {
    return value? value.replace(/_/g, " ") : value;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后像

{{ header|replaceUnderscore}}
Run Code Online (Sandbox Code Playgroud)

您还可以创建一个更通用的版本,该版本将要替换的模式和替换的参数作为参数,例如@ Ash-b对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);
  }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用

{{ header| replace : '_' : ' ' }} 
Run Code Online (Sandbox Code Playgroud)

这是关于stackblitz的演示

  • 谢谢你的解决方案。还通过您的解决方案学习了管道:) (2认同)