9

I get html entities from json file, like: ’ How can I unescape it in html component?

I created custom pipe, but it works only for entities like &:

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

@Pipe({
  name: 'unescape'
})
export class UnescapePipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return unescape(value);
  }

}
  • I'm working with Angular 5.
Adam Pery
  • 1,924
  • 22
  • 21
  • Related [Unescape HTML entities in JavaScript?](https://stackoverflow.com/questions/1912501/unescape-html-entities-in-javascript) – Liam Mar 29 '22 at 08:54

2 Answers2

9

The solution, create next custom pipe:

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

@Pipe({
  name: 'unescape'
})
export class UnescapePipe implements PipeTransform {

  transform(value: any, args?: any): any {
    const doc = new DOMParser().parseFromString(value, 'text/html');
    return doc.documentElement.textContent;
  }

}
Adam Pery
  • 1,924
  • 22
  • 21
1

Still the same : use replace or encodeUri of JavaScript and escape every chars you don't want. The other way is to create a Pipe like you are doing based on regex/replace/escape functions ;)

escape(htmlInput) { 
    htmlInput.replace("&", "and")
} 

escape is now encodeUri and you can also use contains to verify first if you have a matched pattern :)

Robert
  • 7,394
  • 40
  • 45
  • 64
andrea06590
  • 1,259
  • 3
  • 10
  • 22