迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中编码 HTML 实体的简单解决方案

作者:迹忆客 最近更新:2024/03/19 浏览次数:

本文介绍了在 JavaScript 中对 HTML 实体进行编码的最佳解决方案。下面的示例代码将任何字符串转换为 HTML 实体并返回字符串原型。


使用 String.prototype.toHtmlEntities() 将字符串编码为 HTML 实体

在以下 JavaScript 代码中,

  • String.prototype.toHtmlEntities = function().replace() 方法的帮助下返回一个包含 HTML 实体的字符串。
  • .replace() 查找给定字符串的值并将其更改为新的所需/指定值。
  • .prototype 是 JavaScript 中的一个对象。默认情况下,它与函数和对象相关联。
  • String.charCodeAt() 返回在字符串中描述索引的字符的 Unicode。
/**
 * Conversion of string to HTML entities
 */
String.prototype.toHtmlEntities = function() {
  return this.replace(/./gm, function(s) {
    // return "&#" + s.charCodeAt(0) + ";";
    return (s.match(/[a-z0-9\s]+/i)) ? s : '&#' + s.charCodeAt(0) + ';';
  });
};

使用 String.fromHtmlEntities() 对来自 HTML 实体的字符串进行编码

在以下 JavaScript 语句中,我们创建了:

  • String.fromHtmlEntities = function(string) 接收任何包含 HTML 实体的 string
  • 在示例中,.replace() 中给定的字符串值是 /&#\d+;/gm,它被替换为一个 function(s),返回字符串 String.fromCharCode
  • String.fromCharCode 是一种返回由序列生成的字符串的方法。
/**
 * Creation of string from HTML entities
 */
String.fromHtmlEntities = function(string) {
  return (string + '').replace(/&#\d+;/gm, function(s) {
    return String.fromCharCode(s.match(/\d+/gm)[0]);
  })
};

之后,使用如下功能。

  • 这是一个变量 var str,它被初始化为一个包含特殊字符的字符串 (†®¥¨©˙∫ø…ˆƒ∆...)。
  • 函数 .toHtmlEntities 使用这个特殊字符串 var str 被调用。
  • console.log 是 JavaScript 的默认函数,用于在日志框中显示值。
var str = "Dummy Test´†®¥¨©˙∫ø…ˆƒ∆÷∑™ƒ∆æø𣨠ƒ™en tést".toHtmlEntities();
console.log("Entities:", str);
console.log("String:", String.fromHtmlEntities(str));

控制台的输出如下。

"Entities:"
"Test´†®¥¨©˙∫ø…ˆƒ∆÷∑™ƒ∆æø𣨠ƒ™en tést"
"String:"
"Dummy Test´†®¥¨©˙∫ø…ˆƒ∆÷∑™ƒ∆æø𣨠ƒ™en tést"

在 JavaScript 中使用 unescapeHTML() 函数编码 HTML 实体

你可以在线或离线在 JavaScript 编译器上检查这些函数。它可以帮助你显示 string 而无需浏览器读取其 HTML. 这可以用另一种方式来完成。你可以创建 HTML 实体的对象。

  • 变量 var htmlEntities 包含特殊字符和符号的对象。
  • unescapeHTML(str) 函数在 .replace() 条件的帮助下接收字符串和返回值。
var htmlEntities = {
  nbsp: ' ',
  cent: '¢',
  pound: '£',
  yen: '¥',
  euro: '€',
  copy: '©',
  reg: '®',
  lt: '<',
  gt: '>',
  quot: '"',
  amp: '&',
  apos: '\''
};

function unescapeHTML(str) {
  return str.replace(/\&([^;]+);/g, function(entity, entityCode) {
    var match;

    if (entityCode in htmlEntities) {
      return htmlEntities[entityCode];
      /*eslint no-cond-assign: 0*/
    } else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
      return String.fromCharCode(parseInt(match[1], 16));
      /*eslint no-cond-assign: 0*/
    } else if (match = entityCode.match(/^#(\d+)$/)) {
      return String.fromCharCode(~~match[1]);
    } else {
      return entity;
    }
  });
};

JavaScript 中没有任何原生版本的 HTML 实体。如果你只需要基础知识,以便浏览器不会将其解释为 HTML。PHP.js 项目 是一项将每个 PHP 的本地能力移植到 JavaScript 的任务,也包含一个模型。沿着这些思路,我一直保持直截了当,并利用了下面的内容:

function EntitiesHtml(string) {
  return String(string)
      .replace(/&/g, '&amp;')
      .replace(/>/g, '&gt;')
      .replace(/</g, '&lt;')
      .replace(/"/g, '&quot;');
}

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便