【问题标题】:How to replace all underscores to spaces in angular?如何将所有下划线替换为角度空格?
【发布时间】:2020-11-04 11:51:14
【问题描述】:

我的变量:

{{imageGrid.bannerName}}

我的输出:

DINING_LANDING_PAGE_MEAL_PLAN_SUBSCRIBED_USER

如何在angularjs中替换_?

【问题讨论】:

  • 请记住阅读how to ask a good question并相应地编辑您的帖子。
  • 创建一个名为 noUnderscore 的自定义 filter 并像这样使用它:{{ imageGrid.bannerName | noUnderscore }}
  • 有意义@ibrahimmahrir 所以它是可重复使用的
  • 你的意思是 angular (v2+) 还是 angular.js (1.x)?由于您的标题、问题和标签,它不清楚。基本 javascript 代码将与已经回答的相同,但是如果您想在 Angular 和 Angular.js 中创建一个非常不同的指令

标签: javascript angularjs angular angularjs-directive


【解决方案1】:

创建一个名为custom filternoUnderscore,如下所示:

/* the module you want to add this to */.filter("noUnderscore", function () {
    return function (input) {
        return input.replace(/_/g, " ");
    }
});

然后像这样在你的模板中使用它:

{{ imageGrid.bannerName | noUnderscore }}

【讨论】:

    【解决方案2】:

    “DINING_LANDING_PAGE_MEAL_PLAN_SUBSCRIBED_USER”.split(“_”).join(“”)

    【讨论】:

    • 解决了正则表达式的需要,不错
    【解决方案3】:

    试试这个?

    {{imageGrid.bannerName.replace('_', ' ')}}
    

    确定正确的解决方案需要添加标志'g'

    {{imageGrid.bannerName.replace(/_/g, ' ')}}
    

    【讨论】:

    • 此语句仅替换第一次(不是每次)出现。
    • 我试过了,但它取代了第一个。输出:DINING LANDING_PAGE_MEAL_PLAN_UNSUBSCRIBED_USER
    • 使用 g 修饰符也可以执行全局匹配 {{imageGrid.bannerName.replace(/_/g, ' ')}}
    • {{imageGrid.bannerName.replace(/_/g, ' ')}} - 不工作
    【解决方案4】:

    如果您使用 Angular V2+,您可以编写自定义管道

    import { Pipe, PipeTransform } from '@angular/core';
    /*
     * Replace the underscore with space 
    */
    @Pipe({name: 'underscore'})
    export class UnderscorePipe implements PipeTransform {
      transform(value: string): string {
        return  value.replace(/\_/g, ' ');
      }
    }
    

    这个管道必须在你的模块中声明。即AppModule.ts

    import { UnderscorePipe } from './underscore.pipe';
    @NgModule({
      imports: [
        BrowserModule,
        FormsModule,
        HttpClientModule
      ],
      declarations: [
        AppComponent,
        UnderscorePipe
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    在 HTML 端

    {{imageGrid.bannerName | underscore}}
    

    如果您想要更复杂的管道,我们可以传递参数

    自定义管道实现

    import { Pipe, PipeTransform } from '@angular/core';
    /*
     * Replace the the first paremeter with the second parameter 
    */
    @Pipe({name: 'replace'})
    export class ReplacePipe implements PipeTransform {
      transform(value: string, existing: string, latest: string): string {
        return  value.replace(new RegExp('\\'+existing, 'g'), latest);
      }
    }
    

    HTML 文件

     <h2>Hi Please {{value | replace: '_' : ' '}}</h2>
    

    【讨论】:

      猜你喜欢
      • 2015-11-03
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多