我用 Angular 写了一个管道,|用,.
export class AppComponent {
name = 'Name|with|pipes';
}
Run Code Online (Sandbox Code Playgroud)
所需的输出是Name,with,pipes,但我认为它是,N,a,m,e,|,w,i,t,h,|,p,i,p,e,s,
这是管道的代码:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replace'})
export class ReplacePipe implements PipeTransform {
transform(value: string, strToReplace: string, replacementStr: string): string {
if(!value || ! strToReplace || ! replacementStr)
{
return value;
}
return value.replace(new RegExp(strToReplace, 'g'), replacementStr);
}
}
Run Code Online (Sandbox Code Playgroud)
这是StackBlitz上的代码。我怎样才能解决这个问题?
该字符|被解释为正则表达式中的交替字符。您可以借助此答案中给出的方法转义搜索字符串:
escapeStr(str) {
return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
Run Code Online (Sandbox Code Playgroud)
然后使用生成的字符串在管道transform方法中创建正则表达式:
return value.replace(new RegExp(this.escapeStr(strToReplace), 'g'), replacementStr);
Run Code Online (Sandbox Code Playgroud)
使用这种技术,模板标记不必了解实现细节,并且可以正常使用管道:
{{ name | replace : '|' : ',' }}
Run Code Online (Sandbox Code Playgroud)
请参阅此 stackblitz的演示。
你需要这样做或者改变你的管道
{{ name | replace : '[|]' : ',' }}
Run Code Online (Sandbox Code Playgroud)
或者是的,像其他人建议的那样双重逃脱。线索是,在正则表达式下已经有特定的含义,所以你不能直接使用它
| 归档时间: |
|
| 查看次数: |
13928 次 |
| 最近记录: |