I have written a pipe in Angular to replace the character |
with a ,
.
export class AppComponent {
name = 'Name|with|pipes';
}
The desired output is Name,with,pipes
, but I am seeing it as ,N,a,m,e,|,w,i,t,h,|,p,i,p,e,s,
Here's the code for the pipe:
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);
}
}
Here's the code on StackBlitz. How can I fix this?
The character |
is interpreted as the alternation character in the regular expression. You can escape the search string with the help of the method given in this answer:
escapeStr(str) {
return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
The resulting string is then used to create the regular expression in the pipe transform
method:
return value.replace(new RegExp(this.escapeStr(strToReplace), 'g'), replacementStr);
With this technique, the template markup doesn't have to be aware of the implementation details, and can use the pipe normally:
{{ name | replace : '|' : ',' }}
See this stackblitz for a demo.
you need to do it like this or change you pipe
{{ name | replace : '[|]' : ',' }}
or yes, double escape like the others suggest. The clue is, is a specific meaning under regex already, so you can't use it directly
Apparently, you need to escape the character in your html when calling the pipe.
In your app.component.html
try write this line:
{{ name | replace : '\\|' : ',' }}
And it should work. (stackblitz updated here)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With