Utils: Made escapeHtml()/unescapeHtml() more efficient.

This commit is contained in:
satyr 2010-03-29 04:30:44 +09:00
Родитель 05032634de
Коммит b4153a68e9
2 изменённых файлов: 26 добавлений и 12 удалений

Просмотреть файл

@ -826,26 +826,30 @@ function signHMAC(algo, key, str) {
// Useful when you just want to concatenate a bunch of strings into // Useful when you just want to concatenate a bunch of strings into
// an HTML fragment and ensure that everything's escaped properly. // an HTML fragment and ensure that everything's escaped properly.
function escapeHtml(string) ( function escapeHtml(s) String(s).replace(escapeHtml.re, escapeHtml.fn);
String(string) escapeHtml.re = /[&<>\"\']/g;
.replace(/&/g, "&amp;") escapeHtml.fn = function escapeHtml_sub($) {
.replace(/</g, "&lt;") switch ($) {
.replace(/>/g, "&gt;") case "&": return "&amp;";
.replace(/\"/g, "&quot;") case "<": return "&lt;";
.replace(/\'/g, "&#39;")); case ">": return "&gt;";
case '"': return "&quot;";
case "'": return "&#39;";
}
};
// === {{{ Utils.unescapeHtml(string) }}} === // === {{{ Utils.unescapeHtml(string) }}} ===
// Returns a version of the {{{string}}} with all occurrences of HTML character // Returns a version of the {{{string}}} with all occurrences of HTML character
// references (&spades; &#x2665; &#9827; etc.) in it decoded. // references (e.g. &spades; &#x2665; &#9827; etc.) in it decoded.
function unescapeHtml(string) ( function unescapeHtml(s) String(s).replace(unescapeHtml.re, unescapeHtml.fn);
String.replace(string, /&#?\w+;/g, unescapeHtml.parse)); unescapeHtml.re = /(?:&#?\w+;)+/g;
unescapeHtml.parse = function unescapeHtml_parse(ref) { unescapeHtml.fn = function unescapeHtml_parse(ref) {
var {div} = unescapeHtml_parse; var {div} = unescapeHtml_parse;
div.innerHTML = ref; div.innerHTML = ref;
return div.textContent; return div.textContent;
}; };
defineLazyProperty(unescapeHtml.parse, function div() ( defineLazyProperty(unescapeHtml.fn, function div() (
Utils.hiddenWindow.document.createElementNS( Utils.hiddenWindow.document.createElementNS(
"http://www.w3.org/1999/xhtml", "div"))); "http://www.w3.org/1999/xhtml", "div")));

Просмотреть файл

@ -611,6 +611,16 @@ function testUtilsPrefs() {
} }
} }
function testUtilsEscapeUnescapeHtml() {
this.skipIfXPCShell();
var {escapeHtml, unescapeHtml} = Utils;
var html = Utils.hiddenWindow.document.documentElement.innerHTML;
this.assertEquals(
html += "&spades;'&#x2665;&#9827;",
unescapeHtml(unescapeHtml(escapeHtml(escapeHtml(html)))));
}
function testL10nUtilsPropertySelector() { function testL10nUtilsPropertySelector() {
var ps = LocalizationUtils.propertySelector("data:," + encodeURI(<![CDATA[ var ps = LocalizationUtils.propertySelector("data:," + encodeURI(<![CDATA[
foo=%S %S foo=%S %S