【问题标题】:How to replace string in angular 2?如何替换角2中的字符串?
【发布时间】:2017-05-24 14:45:51
【问题描述】:

我在html页面中使用了下面的插值。

<div>{{config.CompanyAddress.replace('\n','<br />')}}</div>

也用过

<div>{{config.CompanyAddress.toString().replace('\n','<br />')}}</div>

但两者都显示如下文本

{{config.CompanyAddress.replace('\n','<br />')}}
{{config.CompanyAddress.toString().replace('\n','<br />')}}

【问题讨论】:

  • 为此创建一个管道。

标签: javascript angular string-interpolation


【解决方案1】:

{{}} 用于字符串插值,结果将始终作为字符串添加。在这种情况下,绑定根本不起作用,因为表达式中包含&lt;&gt;{{}} 没有按预期解释。

<div [innerHTML]="replaceLineBreak(config.CompanyAddress) | safeHtml"></div>

replaceLineBreak(s:string) {
  return s && s.replace('\n','<br />');
}

应该做你想做的。正如@hgoebl 所提到的,replaceLineBreak 如果您在多个地方需要它,也可以将其实现为管道。

Plunker example

提示:不鼓励直接绑定到方法,因为在每个更改检测周期都会调用该方法。仅当输入值更改时才调用纯(默认)管道。因此管道效率更高。

另一种方法是只进行一次替换,并使用替换的换行符绑定到值,而不是重复调用replaceLineBreak

提示:您可能想要替换所有换行符,而不仅仅是第一个。一。那里有足够多的 JS 问题来解释如何做到这一点,因此我没有打扰。

【讨论】:

    【解决方案2】:

    您也可以使用管道:

    import { Pipe, PipeTransform } from '@angular/core';
    @Pipe({name: 'replaceLineBreaks'})
    export class ReplaceLineBreaks implements PipeTransform {
      transform(value: string): string {
        return value.replace(/\n/g, '<br/>');
      }
    }
    

    管道必须包含在您的 @NgModule 声明中才能包含在应用程序中。 要在模板中显示 HTML,您可以使用绑定 outerHTML。

    <span [outerHTML]="config.CompanyAddress | replaceLineBreaks"></span>
    

    【讨论】:

      【解决方案3】:

      我正在寻找一种方法来替换角度模板中变量中的子字符串,但将 substringreplacement 都通过参数传递给管道。

      //TS
      import { Pipe, PipeTransform } from "@angular/core";
      @Pipe({ name: "replaceSubstring" })
      export class ReplaceSubstring implements PipeTransform {
        transform(subject: string, substring: string, replacement: string): string {
      
          //notice the need to instantiate a RegExp object, since passing
          //'substring' directly will NOT work, for example
          //subject.replace(substring, replacement) and
          //subject.replace(`/${substring}/`, replacement) don't work
      
          return subject.replace(new RegExp(substring), replacement);
        }
      }
      
      <!--HTML-->
      <!--Example: remove a dot and the numbers after it, from the end of 'variable'-->
      <!--Parameters in this case are "\\.\\d*`$" and "",
          you can pass as many as you want, separated by colons ':'-->
      
      {{ variable | replaceSubstring: "\\.\\d*`$" : "" }}
      

      【讨论】:

        猜你喜欢
        • 2015-09-24
        • 2016-08-03
        • 1970-01-01
        • 2020-06-16
        • 1970-01-01
        • 2022-01-03
        • 2023-04-09
        相关资源
        最近更新 更多