Tuesday 16 March 2021

How to ignore script tags in an excerpt pipe in angular

I am trying to build an excerpt pipe in my Angular app. The content is comeing in from a json file API which contains HTML. Therefore, I am sanitizing it with [ineerHTML] and. then the pipe for the excerpt cutoff at 90 characters.

Looks like this

<div 
  class="emp-content" 
  (click)="onClick(employee.id)"
  [innerHTML]="employee.content | excerpt:90"></div>

My pipe filter looks like this

  import { Pipe, PipeTransform } from '@angular/core';

  @Pipe({
    name: 'excerpt',
    pure: false
  })
  export class ExcerptFilter implements PipeTransform {
    transform(text: String, length:any ): any {
      if (!text || !length) {
        return text;
      }
      if (text.length > length) {
        return text.substr(0, length) + ' <span class="seemore">... see more</span>';
      }
        return text;
    }
  }

The problem I am having is script tags in the json break the functionality of this pipe. For example, in this case, the 90th character is part of the script tag in the json file so it adds the class="seemore" to it....so weird... Check it out

<div class="emp-content"><p>Brother Michael Mulvaney has been named the UA's new Executive Vice President. <br><br class="seemore">... see more</p></div>

That class should not have been added to the <br/> tag

How can I modify the pipe filter so that it ignores script tags. In other words. ANY content inside < and > or < and />?

Thanks



from How to ignore script tags in an excerpt pipe in angular

No comments:

Post a Comment