Angular Striphtml Tags Pipe

This Angular Pipe that strips html tags with an option to allow useful tags. This Angular Pipe can be useful for displaying html content on your template or storing html content to your back-end. We use JavaScript regular expressions to replace html tags while preserving the tags content.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'stripTags'
})
export class StripTagsPipe implements PipeTransform {
  transform(text: string, ...usefulTags: any[]): string {
    return usefulTags.length > 0
      ? text.replace(new RegExp(`<(?!\/?(${usefulTags.join('|')})\s*\/?)[^>]+>`, 'g'), '')
      : text.replace(/<(?:.|\s)*?>/g, '');
  }

}

And we can use it in our templates as below:

1
2
3
4
5
// Strip all html tags:
  <div>{{htmlText | stripTags}}</div>
// Strip all html tags except pre tags:
  <div>{{htmlText | stripTags: 'pre'}}</div>
  <div [innerHTML]="htmlText | stripTags: 'pre'"></div>

Related Posts

0 Comments

12345

    00