Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Pipe Replace character

Tags:

angular

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?

like image 709
Jake Avatar asked May 09 '19 15:05

Jake


3 Answers

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.

like image 108
ConnorsFan Avatar answered Sep 21 '22 15:09

ConnorsFan


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

like image 38
jcuypers Avatar answered Sep 21 '22 15:09

jcuypers


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)

like image 40
Carbamate Avatar answered Sep 22 '22 15:09

Carbamate