【问题标题】:Use global replace method in Angular 2+ component在 Angular 2+ 组件中使用全局替换方法
【发布时间】:2018-12-16 18:54:43
【问题描述】:

我需要向现有组件添加一个名为“dataTestValue”的新属性。这是一个类似于选项卡的简单组件:

export class TabComponent implements OnInit {

  @Input('active') active = false;
  @Input('title') title: string;

  dataTestValue: string;

  constructor() { }

  ngOnInit() {
    this.dataTestValue = this.title.replace('/ /g', '_');
    console.log(this.dataTestValue);
  }

}

因为“title”属性可以包含空格,我需要替换并将其转换为小写。

我设法只用这个替换了第一个空白:

this.dataTestValue = this.title.replace(' ', '_');

由于某种原因,全局方法不起作用,它只是打印原始值。有什么想法吗?

P.S:如果我使用“ngOnInit”生命周期挂钩,请通知我。

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    从正则表达式中删除单引号:

    this.dataTestValue = this.title.replace(/ /g, '_');
    

    【讨论】:

    • 有效。对不起,我的 JavaScript 技能很差
    【解决方案2】:

    去掉引号

    this.dataTestValue = this.title.replace(/ /g, '_');
    

    或者你也可以使用它

    this.dataTestValue = this.title.replace(/\s+/g, '_');
    

    【讨论】:

      猜你喜欢
      • 2017-02-05
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      • 2016-07-16
      相关资源
      最近更新 更多