Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在角度视图中,如何用空格(';';)替换下划线(307;)?_Javascript_Angular_Typescript - Fatal编程技术网

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

Javascript 在角度视图中,如何用空格(';';)替换下划线(307;)?,javascript,angular,typescript,Javascript,Angular,Typescript,我在表的标题中显示数组键,键中有下划线。我想在html表中用空格替换下划线。我不想在组件中这样做,因为我有其他要求 <table> <thead> <tr> <th *ngFor="let header of printFields">{{header}}</th> </tr> </thead> <tbody> <

我在表的标题中显示数组键,键中有下划线。我想在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>

{{header}}
{{ab.Bill_Number}
.....
.....

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

 {{ header.replace('_', ' ') }} 
否则你必须使用过滤器

App.filter('strReplace', function () {
 return function (input, from, to) {
 input = input || '';
 from = from || '';
 to = to || '';
 return input.replace(new RegExp(from, 'g'), to);
 };
});
像这样使用它

 {{ header | strReplace:'_':' ' }}
{{ header|replaceUnderscore}}

希望这有帮助:-)

只需使用regex即可-

header.replace(/_/g, " "); // if you need space
header.replace(/_/g, ""); //if you don't need space
你可以用管子

然后像这样使用它

 {{ header | strReplace:'_':' ' }}
{{ header|replaceUnderscore}}
您还可以制作一个更通用的版本,将要替换的模式和替换作为参数,如@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);
  }
}
像这样使用它

{{ header| replace : '_' : ' ' }} 

下面是一个演示

您可以执行以下操作:

  • 创建一个管道
  • 在transform方法中,编写以下代码

    transform(value: any, args?: any): string {
        let [first, ...rest] = value.split("_");
        if (rest.length === 0) return first;
        else return `${first} ${rest.join(" ")}`;
    }
    
    此代码将处理键是否有下划线

    • 键=角度_7=>角度7
    • 键=角度=>角度
  • 本例第6条:

     underscore(selectkpi){
        this.selectedUnderKpi = selectkpi.replace(' ', '_');
        var a = this.selectedUnderKpi.
        console.log("ini = ",a);
      }
    

    在哪里添加第二个?它看起来像是一个有角度的JS代码。我使用的是Angular2,您可以将代码添加到脚本文件中,您在其中声明应用程序的文件头的类型是什么?这是字符串类型吗?好的,您可以创建一个方法并将头传递给该函数,在函数内部您可以编写上述代码。谢谢您的解决方案。还通过您的解决方案学习了管道:)