[英]Encode HTML entities in JavaScript
我在一个允许用户输入内容的 CMS 中工作。 问题是当他们添加符号®
,它可能无法在所有浏览器中很好地显示。 我想设置一个必须搜索的符号列表,然后转换为相应的html实体。 例如
® => ®
& => &
© => ©
™ => ™
转换后需要用<sup>
标签包裹,结果如下:
®
=> <sup>®</sup>
因为需要特定的字体大小和填充样式:
sup { font-size: 0.6em; padding-top: 0.2em; }
JavaScript 会是这样吗?
var regs = document.querySelectorAll('®');
for ( var i = 0, l = imgs.length; i < l; ++i ) {
var [?] = regs[i];
var [?] = document.createElement('sup');
img.parentNode.insertBefore([?]);
div.appendChild([?]);
}
其中“[?]”表示有一些我不确定的事情。
额外细节:
您可以使用正则表达式将给定 unicode 范围内的任何字符替换为其等效的 html 实体。 代码看起来像这样:
var encodedStr = rawStr.replace(/[\u00A0-\u9999<>\&]/g, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
此代码将替换给定范围内的所有字符(unicode 00A0 - 9999,以及&符号,大于和小于)与其等效的 html 实体,这只是&#nnn;
其中nnn
是我们从charCodeAt
获得的 unicode 值。
在此处查看操作: http : //jsfiddle.net/E3EqX/13/ (此示例使用 jQuery 作为示例中使用的元素选择器。上面的基本代码本身不使用 jQuery)
进行这些转换并不能解决所有问题——确保您使用的是 UTF8 字符编码,确保您的数据库以 UTF8 存储字符串。 您仍然可能会看到字符显示不正确的情况,这取决于系统字体配置和您无法控制的其他问题。
文档
当前接受的答案有几个问题。 这篇文章解释了它们,并提供了一个更强大的解决方案。 该答案中建议的解决方案以前有:
var encodedStr = rawStr.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
i
标志是多余的,因为从 U+00A0 到 U+9999 范围内的任何 Unicode 符号都没有在同一范围之外的大写/小写变体。
m
标志是多余的,因为^
或$
未在正则表达式中使用。
为什么范围是 U+00A0 到 U+9999? 似乎是随意的。
无论如何,对于在输入中正确编码除安全和可打印 ASCII 符号之外的所有符号(包括星形符号!)并实现所有命名字符引用(不仅仅是 HTML4 中的那些)的解决方案,请使用he库(免责声明:这个库是我的) )。 从它的自述文件:
he (代表“HTML 实体”)是一个用 JavaScript 编写的强大的 HTML 实体编码器/解码器。 它支持所有标准化的 HTML 命名字符引用, 像浏览器一样处理模糊的&符号和其他边缘情况,具有广泛的测试套件,并且——与许多其他 JavaScript 解决方案相反——他可以很好地处理星体 Unicode 符号。 提供在线演示。
另请参阅此相关堆栈溢出答案。
我遇到了同样的问题并创建了 2 个函数来创建实体并将它们转换回正常字符。 以下方法将任何字符串转换为 HTML 实体并返回字符串原型
/**
* Convert a 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) + ";";
});
};
/**
* Create 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 = "Test´†®¥¨©˙∫ø…ˆƒ∆÷∑™ƒ∆æø𣨠ƒ™en tést".toHtmlEntities();
console.log("Entities:", str);
console.log("String:", String.fromHtmlEntities(str));
控制台输出:
Entities: Dit is e´†®¥¨©˙∫ø…ˆƒ∆÷∑™ƒ∆æø𣨠ƒ™en t£eést
String: Dit is e´†®¥¨©˙∫ø…ˆƒ∆÷∑™ƒ∆æø𣨠ƒ™en t£eést
没有任何库,如果您不需要支持 IE < 9,您可以创建一个 html 元素并使用Node.textContent设置其内容:
var str = "<this is not a tag>";
var p = document.createElement("p");
p.textContent = str;
var converted = p.innerHTML;
这是一个例子: https : //jsfiddle.net/1erdhehv/
更新:这仅适用于 HTML 标记实体(&、< 和 >)。
你可以用这个。
var escapeChars = {
'¢' : 'cent',
'£' : 'pound',
'¥' : 'yen',
'€': 'euro',
'©' :'copy',
'®' : 'reg',
'<' : 'lt',
'>' : 'gt',
'"' : 'quot',
'&' : 'amp',
'\'' : '#39'
};
var regexString = '[';
for(var key in escapeChars) {
regexString += key;
}
regexString += ']';
var regex = new RegExp( regexString, 'g');
function escapeHTML(str) {
return str.replace(regex, function(m) {
return '&' + escapeChars[m] + ';';
});
};
https://github.com/epeli/underscore.string/blob/master/escapeHTML.js
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;
}
});
};
如果您想避免多次编码 html 实体
function encodeHTML(str){
return str.replace(/([\u00A0-\u9999<>&])(.|$)/g, function(full, char, next) {
if(char !== '&' || next !== '#'){
if(/[\u00A0-\u9999<>&]/.test(next))
next = '&#' + next.charCodeAt(0) + ';';
return '&#' + char.charCodeAt(0) + ';' + next;
}
return full;
});
}
function decodeHTML(str){
return str.replace(/&#([0-9]+);/g, function(full, int) {
return String.fromCharCode(parseInt(int));
});
}
# 例子
var text = "<a>Content © <#>&<&#># </a>";
text = encodeHTML(text);
console.log("Encode 1 times: " + text);
// <a>Content © <#>&<&#># </a>
text = encodeHTML(text);
console.log("Encode 2 times: " + text);
// <a>Content © <#>&<&#># </a>
text = decodeHTML(text);
console.log("Decoded: " + text);
// <a>Content © <#>&<&#># </a>
如果您已经在使用 jQuery,请尝试html()
。
$('<div>').text('<script>alert("gotcha!")</script>').html()
// "<script>alert("gotcha!")</script>"
实例化内存中的文本节点,并在其上调用html()
。
它很丑,浪费了一点内存,我不知道它是否像he
库一样彻底,但如果你已经在使用 jQuery,也许这对你来说是一个选择。
取自 Felix Geisendörfer 的博文Encode HTML entity with jQuery 。
ESCAPE CODES
保留字符必须由 HTML 转义:我们可以使用字符转义来表示 HTML、XHTML 或 XML 中的任何 Unicode 字符 [例如:& - U+00026] 仅使用 ASCII 字符。 数字字符引用[例如: &
(&) - &
] & 命名字符引用[例如: &
] 是character escape used in markup
的character escape used in markup
类型。
原始字符XML 实体替换XML 数字替换
< < <
> > >
“ " "
& & &
' ' '
为了在网页中将 HTML 标签显示为普通形式,我们使用<pre>
、 <code>
标签或者我们可以对它们进行转义。 通过用字符串"&"
替换任何出现的"&"
字符来转义字符串以及字符串">"
">"
出现的任何">"
字符 . 例如: stackoverflow post
function escapeCharEntities() {
var map = {
"&": "&",
"<": "<",
">": ">",
"\"": """,
"'": "'"
};
return map;
}
var mapkeys = '', mapvalues = '';
var html = {
encodeRex : function () {
return new RegExp(mapkeys, 'g'); // "[&<>"']"
},
decodeRex : function () {
return new RegExp(mapvalues, 'g'); // "(&|<|>|"|')"
},
encodeMap : JSON.parse( JSON.stringify( escapeCharEntities () ) ), // json = {&: "&", <: "<", >: ">", ": """, ': "'"}
decodeMap : JSON.parse( JSON.stringify( swapJsonKeyValues( escapeCharEntities () ) ) ),
encode : function ( str ) {
var encodeRexs = html.encodeRex();
console.log('Encode Rex: ', encodeRexs); // /[&<>"']/gm
return str.replace(encodeRexs, function(m) { console.log('Encode M: ', m); return html.encodeMap[m]; }); // m = < " > SpecialChars
},
decode : function ( str ) {
var decodeRexs = html.decodeRex();
console.log('Decode Rex: ', decodeRexs); // /(&|<|>|"|')/g
return str.replace(decodeRexs, function(m) { console.log('Decode M: ', m); return html.decodeMap[m]; }); // m = < " >
}
};
function swapJsonKeyValues ( json ) {
var count = Object.keys( json ).length;
var obj = {};
var keys = '[', val = '(', keysCount = 1;
for(var key in json) {
if ( json.hasOwnProperty( key ) ) {
obj[ json[ key ] ] = key;
keys += key;
if( keysCount < count ) {
val += json[ key ]+'|';
} else {
val += json[ key ];
}
keysCount++;
}
}
keys += ']'; val += ')';
console.log( keys, ' == ', val);
mapkeys = keys;
mapvalues = val;
return obj;
}
console.log('Encode: ', html.encode('<input type="password" name="password" value=""/>') );
console.log('Decode: ', html.decode(html.encode('<input type="password" name="password" value=""/>')) );
O/P:
Encode: <input type="password" name="password" value=""/>
Decode: <input type="password" name="password" value=""/>
var htmlEntities = [
{regex:/&/g,entity:'&'},
{regex:/>/g,entity:'>'},
{regex:/</g,entity:'<'},
{regex:/"/g,entity:'"'},
{regex:/á/g,entity:'á'},
{regex:/é/g,entity:'é'},
{regex:/í/g,entity:'í'},
{regex:/ó/g,entity:'ó'},
{regex:/ú/g,entity:'ú'}
];
total = <some string value>
for(v in htmlEntities){
total = total.replace(htmlEntities[v].regex, htmlEntities[v].entity);
}
阵列解决方案
有时您只想对每个字符进行编码...此函数替换 regxp 中的“除任何之外的一切”。
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
function encode(w) { return w.replace(/[^]/g, function(w) { return "&#" + w.charCodeAt(0) + ";"; }); } test.value=encode(document.body.innerHTML.trim());
<textarea id=test rows=11 cols=55>www.WHAK.com</textarea>
查看来自 Ourcodeworld Ourcodeworld的教程- 使用 javascript 编码和解码 html 实体
最重要的是,他图书馆的例子
he.encode('foo © bar ≠ baz ???? qux');
// → 'foo © bar ≠ baz 𝌆 qux'
// Passing an `options` object to `encode`, to explicitly encode all symbols:
he.encode('foo © bar ≠ baz ???? qux', {
'encodeEverything': true
});
he.decode('foo © bar ≠ baz 𝌆 qux');
// → 'foo © bar ≠ baz ???? qux'
这个库可能会让你的编码更容易,更好地管理。 它很受欢迎,定期更新并遵循 HTML 规范。 它本身没有依赖关系,可以在package.json 中看到
这是我实现编码的方式。 我从上面给出的答案中获得灵感。
function encodeHTML(str) { const code = { ' ' : ' ', '¢' : '¢', '£' : '£', '¥' : '¥', '€' : '€', '©' : '©', '®' : '®', '<' : '<', '>' : '>', '"' : '"', '&' : '&', '\\'' : ''' }; return str.replace(/[\ -\香<>\\&''""]/gm, (i)=>code[i]); } // TEST console.log(encodeHTML("Dolce & Gabbana")); console.log(encodeHTML("Hamburgers < Pizza < Tacos")); console.log(encodeHTML("Sixty > twelve")); console.log(encodeHTML('Stuff in "quotation marks"')); console.log(encodeHTML("Schindler's List")); console.log(encodeHTML("<>"));
编码或解码 HTML 实体的简便方法之一
只用一个参数调用一个函数......
解码 HTML 实体
function decodeHTMLEntities(text) {
var textArea = document.createElement('textarea');
textArea.innerHTML = text;
return textArea.value;
}
解码 HTML 实体 (JQuery)
function decodeHTMLEntities(text) {
return $("<textarea/>").html(text).text();
}
编码 HTML 实体
function encodeHTMLEntities(text) {
var textArea = document.createElement('textarea');
textArea.innerText = text;
return textArea.innerHTML;
}
编码 HTML 实体 (JQuery)
function encodeHTMLEntities(text) {
return $("<textarea/>").text(text).html();
}
htmlentities()转换 HTML 实体
因此,我们构建了一个常量,其中包含我们要转换的 html 标签。
const htmlEntities = [
{regex:'&',entity:'&'},
{regex:'>',entity:'>'},
{regex:'<',entity:'<'}
];
我们构建了一个函数,将所有相应的 html 字符转换为字符串:Html ==> String
function htmlentities (s){
var reg;
for (v in htmlEntities) {
reg = new RegExp(htmlEntities[v].regex, 'g');
s = s.replace(reg, htmlEntities[v].entity);
}
return s;
}
为了解码,我们构建了一个反向函数,它将所有字符串转换为它们的等效 html 。 字符串 ==> html
function html_entities_decode (s){
var reg;
for (v in htmlEntities) {
reg = new RegExp(htmlEntities[v].entity, 'g');
s = s.replace(reg, htmlEntities[v].regex);
}
return s;
}
之后,我们可以使用 encodeURIComponent() 对所有其他特殊字符 (é è ...) 进行编码
用例
var s = '<div> God bless you guy </div> '
var h = encodeURIComponent(htmlentities(s)); /** To encode */
h = html_entities_decode(decodeURIComponent(h)); /** To decode */
函数 htmlEntityReplacer(encoded_text) { var decoded_text = encoding_text;
const all_entities = [{ /* source: https://www.w3schools.com/html/html_entities.asp */
encoded: ` `,
decoded: ` `
}, {
encoded: `<`,
decoded: `<`
}, {
encoded: `>`,
decoded: `>`
}, {
encoded: `&`,
decoded: `&`
}, {
encoded: `"`,
decoded: `"`
}, {
encoded: `'`,
decoded: `'`
}, {
encoded: `¢`,
decoded: `¢`
}, {
encoded: `£`,
decoded: `£`
}, {
encoded: `¥`,
decoded: `yen`
}, {
encoded: `€`,
decoded: `€`
}, {
encoded: `©`,
decoded: `©`
}, {
encoded: `®`,
decoded: `®`
}]
for (i = 0; i < all_entities.length; i++) {
var decoded_text = decoded_text.replace(new RegExp(all_entities[i].encoded, 'g'), all_entities[i].decoded)
}
return decoded_text;
}
// 对于节点或香草
您可以使用charCodeAt()
方法检查指定字符的值是否大于 127,并使用toString(16)
将其转换为数字字符引用。
replaceHtmlEntities(text) {
var tagsToReplace = {
'&': '&',
'<': '<',
'>': '>',
};
var newtext = text;
for (var tag in tagsToReplace) {
if (Reflect.apply({}.hasOwnProperty, this, [tagsToReplace, tag])) {
var regex = new RegExp(tag, 'g');
newtext = newtext.replace(regex, tagsToReplace[tag]);
}
}
return newtext;
}
<!DOCTYPE html> <html> <style> button { backround: #ccc; padding: 14px; width: 400px; font-size: 32px; } #demo { font-size: 20px; font-family: Arial; font-weight: bold; } </style> <body> <p>Click the button to decode.</p> <button onclick="entitycode()">Html Code</button> <p id="demo"></p> <script> function entitycode() { var uri = "quotation = ark __ ' = apostrophe __ & = ampersand __ < = less-than __ > = greater-than __ non- = reaking space __ ¡ = inverted exclamation mark __ ¢ = cent __ £ = pound __ ¤ = currency __ ¥ = yen __ ¦ = broken vertical bar __ § = section __ ¨ = spacing diaeresis __ © = copyright __ ª = feminine ordinal indicator __ « = angle quotation mark (left) __ ¬ = negation __ ­ = soft hyphen __ ® = registered trademark __ ¯ = spacing macron __ ° = degree __ ± = plus-or-minus __ ² = superscript 2 __ ³ = superscript 3 __ ´ = spacing acute __ µ = micro __ ¶ = paragraph __ · = middle dot __ ¸ = spacing cedilla __ ¹ = superscript 1 __ º = masculine ordinal indicator __ » = angle quotation mark (right) __ ¼ = fraction 1/4 __ ½ = fraction 1/2 __ ¾ = fraction 3/4 __ ¿ = inverted question mark __ × = multiplication __ ÷ = division __ À = capital a, grave accent __ Á = capital a, acute accent __ Â = capital a, circumflex accent __ Ã = capital a, tilde __ Ä = capital a, umlaut mark __ Å = capital a, ring __ Æ = capital ae __ Ç = capital c, cedilla __ È = capital e, grave accent __ É = capital e, acute accent __ Ê = capital e, circumflex accent __ Ë = capital e, umlaut mark __ Ì = capital i, grave accent __ Í = capital i, acute accent __ Î = capital i, circumflex accent __ Ï = capital i, umlaut mark __ Ð = capital eth, Icelandic __ Ñ = capital n, tilde __ Ò = capital o, grave accent __ Ó = capital o, acute accent __ Ô = capital o, circumflex accent __ Õ = capital o, tilde __ Ö = capital o, umlaut mark __ Ø = capital o, slash __ Ù = capital u, grave accent __ Ú = capital u, acute accent __ Û = capital u, circumflex accent __ Ü = capital u, umlaut mark __ Ý = capital y, acute accent __ Þ = capital THORN, Icelandic __ ß = small sharp s, German __ à = small a, grave accent __ á = small a, acute accent __ â = small a, circumflex accent __ ã = small a, tilde __ ä = small a, umlaut mark __ å = small a, ring __ æ = small ae __ ç = small c, cedilla __ è = small e, grave accent __ é = small e, acute accent __ ê = small e, circumflex accent __ ë = small e, umlaut mark __ ì = small i, grave accent __ í = small i, acute accent __ î = small i, circumflex accent __ ï = small i, umlaut mark __ ð = small eth, Icelandic __ ñ = small n, tilde __ ò = small o, grave accent __ ó = small o, acute accent __ ô = small o, circumflex accent __ õ = small o, tilde __ ö = small o, umlaut mark __ ø = small o, slash __ ù = small u, grave accent __ ú = small u, acute accent __ û = small u, circumflex accent __ ü = small u, umlaut mark __ ý = small y, acute accent __ þ = small thorn, Icelandic __ ÿ = small y, umlaut mark"; var enc = encodeURI(uri); var dec = decodeURI(enc); var res = dec; document.getElementById("demo").innerHTML = res; } </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.