角管:无法替换/

时间:2017-06-06 14:21:17

标签: javascript angular ionic-framework ionic2

我一直在尝试创建一个管道来替换消息中的某些字符,这是管道的代码:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
  transform(value: string): string {
    console.log(value);
    let newValue = value.replace(/\n/g, '<br>');
    console.log(newValue);
    return `${newValue}`;
  }
}

我在这样的网页上使用它:

  <ion-card-content [innerHtml]="message | linky | replace"></ion-card-content>

问题:当替换语句是这样的时候它起作用:

let newValue = value.replace('bit', '<br>');

但是当它看起来像这样时没有做任何事情:(我需要让它为此工作)

let newValue = value.replace(/\n/g, '<br>');

我似乎无法弄清楚我哪里出错了。

4 个答案:

答案 0 :(得分:0)

当你说它没有工作时,这意味着console.log(newValue)输出为&#34;某些东西\ n&#34;而不是&#34;东西&#34;?是否有任何类型的错误消息?

我刚接受了您的确切代码并对其进行了测试here并且确实有效。

var value = "asd \n more stuff";
console.log(value)
let newValue = value.replace(/\n/g, '<br>');
console.log(newValue)

答案 1 :(得分:0)

您确定\n字符在您的字符串中吗?它可能是一个字符串。试一试:let newValue = value.replace(/\\n/g, '<br>');您需要的原因是因为您的字符串实际上是"\n"而不是newline字符。在正则表达式\n中是换行符,\\n"\n"为字符串。

答案 2 :(得分:0)

我能够通过<br> double quotes并向\添加额外的\n来实现目标。我不知道为什么我需要这样做才能让它发挥作用但它现在完美无缺。这是解决方案:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
  transform(value: string): string {
    console.log(value);
    if(value) {
    let newValue = value.replace(/\\n/g, "<br>").replace(/&/g, "&amp;");
    console.log(newValue);
    return `${newValue}`;
  }
  }
}

答案 3 :(得分:0)

我当时正在处理返回线路,但只是发现你可以用css轻松地显示这些线路的跳跃。 { white-space: pre; }