【问题标题】:Converting special character entity name into actual symbols将特殊字符实体名称转换为实际符号
【发布时间】:2016-01-05 16:49:07
【问题描述】:

我得到一个 json 作为回报,其值为 &" 和更多特殊字符。我想要一个通用的解决方案将它们全部转换为它们的实际值,例如 &amp as &,&quot 到 ",等等。 我不想使用像下面的代码这样的东西,因为将来会出现更多不同的符号-

    $scope.oldNotification[i].shorttext=$scope.oldNotification[i].shorttext.replace(/&/g, '&');
    $scope.oldNotification[i].shorttext=$scope.oldNotification[i].shorttext.replace(/&lt;/g, '<');
    $scope.oldNotification[i].shorttext=$scope.oldNotification[i].shorttext.replace(/&gt;/g, '>');
    $scope.oldNotification[i].shorttext=$scope.oldNotification[i].shorttext.replace(/&quot;/g, '"');
    $scope.oldNotification[i].shorttext=$scope.oldNotification[i].shorttext.replace(/&#039;/g, "'");

是否有任何 api 来处理这些值并将它们转换为它们的实际值? 我正在使用 angularJs。

【问题讨论】:

  • 那么,你需要解析HTML吗?
  • 我想解析从 JSON 获取的数据,然后将它们显示在 HTML 页面中。
  • 这里没有处理引号(双引号和单引号)...我需要完全准确...
  • 为了清晰起见,我更新了示例

标签: javascript html angularjs entity symbols


【解决方案1】:

由于您使用的是 Angular,因此您可以使用 jQuery。

只需使用 jQuery 创建一个元素,然后使用其 text() 属性对其进行解析

var str = $( "<span>&quotDale ca&ntilde;a&quot&#169;</span>" ).text();
console.log(str);

输出是“Dale caña”©

您需要将字符串放在有效的 html 标记中,例如 '&lt;span&gt;'+yourtext+'&lt;/span&gt;'

Fiddle demo

点击“运行”并打开浏览器的控制台

【讨论】:

    【解决方案2】:

    得到答案...为所有角色工作(我检查过)...

    $scope.oldNotification[i].shorttext=$('<textarea />').html($scope.oldNotification[i].shorttext).text();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多