什么是实体[x]

What is Entity[x]?

本文关键字:实体 什么      更新时间:2023-09-26

我在读Javascript: The Good Parts

作者有一个闭包函数:

return this.replace(/&([^&;]+);/g,
 function (a, b) {
 var r = entity[b];
 return typeof r === 'string' ? r : a;
 }

我不确定ENTITY是什么功能

JavaScript中没有这样的关键字,至少在ECMAScript7 (current)之前是这样。唯一可以使用这些类型的括号[]的对象是某种数据结构(对象、数组等)。所以这个动作entyty[b]将在结构entity中获取由键b表示的数据。

在这个特殊的例子中,b的值将表示括号([^&;]+)中正则表达式的所有匹配子字符串(在文档https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace中查看原因),它将具有结构&something;,这是一个常规HTML实体的样子。例如,它可以是>,这是>等的HTML实体。

所以作者真正的意思是:

var entity = {
   'gt': '>',
   'lt': '<',
   // other HTML entities mapping
};
var str = "&gt;&lt;&period;";
str = str.replace(/&([^&;]+);/g,
 function (a, b) {
    var r = entity[b];
    return typeof r === 'string' ? r : a; // checks if the entity existed in your entity collection, otherwise return the original string
 });
console.log(str);

结果是:><&period;。因为entity里面没有&period;

因此,作者提出了一种算法,将HTML实体字符串转换为具有其真实字符表示的字符串。您可以使用此资源进一步开发:https://dev.w3.org/html5/html-author/charref

干杯!