Douglas Crockford: entityify & deentityify

时间:2023-03-08 17:19:48

大神之字符与字符实体的相互转换方法

// & to &
if (!String.prototype.entityify) {
String.prototype.entityify = function () {
return this.replace(/&/g, "&").
replace(/</g, "&lt;").
replace(/>/g, "&gt;").
replace(/\"/g, "&quot;");
};
} // &amp; to &
if (!String.prototype.deentityify) {
String.prototype.deentityify = function () {
return this.replace(/&amp;/g, "&").
replace(/&lt;/g, "<").
replace(/&gt;/g, ">").
replace(/&quot;/g, "\"");
};
} var sourceStr = '<p>"a&b"</p>'; var entityStr = sourceStr.entityify();
console.log(entityStr); // &lt;p&gt;&quot;a&amp;b&quot;&lt;/p&gt; var deentityStr = entityStr.deentityify();
console.log(deentityStr); // <p>"a&b"</p>