更新时间:2023-02-12 18:47:50
您可以replace 所有程式,不使用命名实体:
You can just replace everything programmatically, not using named entities:
return input.replace(/[^ -~]/g, function(chr) {
// ^^^^^^
// this is a regexp for "everything than printable ASCII-characters"
// and even works in a ASCII-only charset. Identic: [^\u0020-\u007E]
return "&#"+chr.charCodeAt(0)+";";
});
如果要使用命名实体,可以将其与键值映射像@jackwanders的答案):
If you want to use named entities, you can combine this with a key-value-map (as like in @jackwanders answer):
var chars = {
"á" : "á",
"Á" : "Á",
"é" : "é",
"É" : "É",
...
}
return input.replace(/[^ -~]/g, function(chr) {
return (chr in chars)
? chars[chr]
: "&#"+chr.charCodeAt(0)+";";
});
但是,您永远不需要使用html实体在JavaScript中。使用UTF8作为一切的字符编码,它将工作。
However, you should never need to use html entities in JavaScript. Use UTF8 as the character encoding for everything, and it will work.