0

I am attempting to create a custom pipe that will replace one character with another (use case: replacing hyphenated words with space separated words), but I cannot seem to get it working after following online guides and the Angular docs.

stackblitz

pipe.ts

@Pipe({
  name: 'replace'
})
export class ReplacePipe implements PipeTransform {

  transform(value: string, replace: string, withThis: string): any {
    return value.replace(replace, withThis);
  }

}

html usage

<!-- hyphenate = 'some-hyphenated-string' -->

<div>{{hyphenated | replace: {replace: '-', withThis: ' '} }}</div>
physicsboy
  • 5,656
  • 17
  • 70
  • 119
  • Possible duplicate of [How do I call an Angular 2 pipe with multiple arguments?](https://stackoverflow.com/questions/36816788/how-do-i-call-an-angular-2-pipe-with-multiple-arguments) – AmmoPT Aug 29 '18 at 14:16
  • is there a reason for not just using the `replace` method inline with the html? `{{hyphenated.replace('-', ' ')}}` – jtate Aug 29 '18 at 14:18
  • @jtate That would reevaluate the replacement in every change detection cycle. (pure) pipes cache the result. – Ingo Bürk Aug 29 '18 at 14:22

1 Answers1

2

1) You're not calling your custom pipe correctly:

Instead of:

<div>{{hyphenated | replace: {replace: '-', withThis: ' '} }}</div>

Use:

<div>{{hyphenated | replace: '-': ' '}}</div>

2) Your replace usage only replaces the first occurrence in the string:

Instead of:

return value.replace(replace, withThis);

Use:

return value.replace(new RegExp(replace, 'g'), withThis);

Updated stackblitz

AmmoPT
  • 958
  • 1
  • 9
  • 16