What the right way unescape html entities in Angular?

*爱你&永不变心* 提交于 2020-02-01 03:47:05

问题


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.

回答1:


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

}



回答2:


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 :)



来源:https://stackoverflow.com/questions/47378033/what-the-right-way-unescape-html-entities-in-angular

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!