首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将angular中的所有下划线都替换为空格?

如何将angular中的所有下划线都替换为空格?
EN

Stack Overflow用户
提问于 2020-07-15 11:23:51
回答 4查看 688关注 0票数 1

我的变量:

代码语言:javascript
复制
{{imageGrid.bannerName}}

我的输出:

代码语言:javascript
复制
DINING_LANDING_PAGE_MEAL_PLAN_SUBSCRIBED_USER

如何替换angularjs中的_?

EN

Stack Overflow用户

发布于 2020-07-15 11:48:12

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

代码语言:javascript
复制
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

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

在HTML端

代码语言:javascript
复制
{{imageGrid.bannerName | underscore}}

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

自定义管道实现

代码语言:javascript
复制
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文件

代码语言:javascript
复制
 <h2>Hi Please {{value | replace: '_' : ' '}}</h2>
票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62907111

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档