What the right way unescape html entities in Angul

2020-07-10 08:51发布

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.

2条回答
爷、活的狠高调
2楼-- · 2020-07-10 09:36

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;
  }

}

查看更多
家丑人穷心不美
3楼-- · 2020-07-10 09:38

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") }

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

查看更多
登录 后发表回答