【问题标题】:What the right way unescape html entities in Angular?在Angular中取消转义html实体的正确方法是什么?
【发布时间】:2017-11-19 14:35:04
【问题描述】:

我从 json 文件中获取 html 实体,例如:’ 如何在 html 组件中取消转义?

我创建了自定义管道,但它仅适用于 & 之类的实体:

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

}
  • 我正在使用 Angular 5。

【问题讨论】:

    标签: angular escaping


    【解决方案1】:

    解决方案,创建下一个自定义管道:

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

      还是一样:使用 JavaScript 的 replace 或 encodeUri 并转义您不想要的每个字符。另一种方法是像您一样基于正则表达式/替换/转义函数创建一个管道;)

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

      escape 现在是 encodeUri,如果你有匹配的模式,你也可以先使用 contains 来验证:)

      【讨论】:

      • 这似乎与问题无关。问题不是如何转义 url,而是如何un转义它。
      猜你喜欢
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多