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>
3
  • Possible duplicate of How do I call an Angular 2 pipe with multiple arguments? Commented Aug 29, 2018 at 14:16
  • is there a reason for not just using the replace method inline with the html? {{hyphenated.replace('-', ' ')}} Commented Aug 29, 2018 at 14:18
  • @jtate That would reevaluate the replacement in every change detection cycle. (pure) pipes cache the result. Commented Aug 29, 2018 at 14:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the pointers :-) I knew I was going wrong somewhere!
@physicsboy Please consider accepting the answer if it indeed answered your question.
I had to wait for the time limit :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.