我使用JavaScript从隐藏字段中拉出一个值并在文本框中显示它。隐藏字段中的值被编码。

例如,

<input id='hiddenId' type='hidden' value='chalk &amp; cheese' />

被卷入

<input type='text' value='chalk &amp; cheese' />

通过一些jQuery来获取隐藏字段的值(在这一点上,我失去了编码):

$('#hiddenId').attr('value')

问题是当我读粉笔&cheese从隐藏字段,JavaScript似乎失去了编码。我不希望价值是粉笔和奶酪。我想要字面上的amp;被保留。

是否有JavaScript库或jQuery方法可以对字符串进行html编码?


当前回答

Necromancing。 这当然不需要jQuery ! 下面是来自System.Web.HttpUtility的JavaScript端口(c# -免责声明:没有经过很好的测试):

"use strict";
function htmlDecode(s) {
    if (s == null)
        return null;
    if (s.length == 0)
        return "";
    if (s.indexOf('&') == -1)
        return s;
    function isDigit(str) {
        return /^\d+$/.test(str);
    }
    function isHexDigit(str) {
        return /[0-9A-Fa-f]{6}/g.test(str);
    }
    function initEntities() {
        var entities = {};
        entities["nbsp"] = '\u00A0';
        entities["iexcl"] = '\u00A1';
        entities["cent"] = '\u00A2';
        entities["pound"] = '\u00A3';
        entities["curren"] = '\u00A4';
        entities["yen"] = '\u00A5';
        entities["brvbar"] = '\u00A6';
        entities["sect"] = '\u00A7';
        entities["uml"] = '\u00A8';
        entities["copy"] = '\u00A9';
        entities["ordf"] = '\u00AA';
        entities["laquo"] = '\u00AB';
        entities["not"] = '\u00AC';
        entities["shy"] = '\u00AD';
        entities["reg"] = '\u00AE';
        entities["macr"] = '\u00AF';
        entities["deg"] = '\u00B0';
        entities["plusmn"] = '\u00B1';
        entities["sup2"] = '\u00B2';
        entities["sup3"] = '\u00B3';
        entities["acute"] = '\u00B4';
        entities["micro"] = '\u00B5';
        entities["para"] = '\u00B6';
        entities["middot"] = '\u00B7';
        entities["cedil"] = '\u00B8';
        entities["sup1"] = '\u00B9';
        entities["ordm"] = '\u00BA';
        entities["raquo"] = '\u00BB';
        entities["frac14"] = '\u00BC';
        entities["frac12"] = '\u00BD';
        entities["frac34"] = '\u00BE';
        entities["iquest"] = '\u00BF';
        entities["Agrave"] = '\u00C0';
        entities["Aacute"] = '\u00C1';
        entities["Acirc"] = '\u00C2';
        entities["Atilde"] = '\u00C3';
        entities["Auml"] = '\u00C4';
        entities["Aring"] = '\u00C5';
        entities["AElig"] = '\u00C6';
        entities["Ccedil"] = '\u00C7';
        entities["Egrave"] = '\u00C8';
        entities["Eacute"] = '\u00C9';
        entities["Ecirc"] = '\u00CA';
        entities["Euml"] = '\u00CB';
        entities["Igrave"] = '\u00CC';
        entities["Iacute"] = '\u00CD';
        entities["Icirc"] = '\u00CE';
        entities["Iuml"] = '\u00CF';
        entities["ETH"] = '\u00D0';
        entities["Ntilde"] = '\u00D1';
        entities["Ograve"] = '\u00D2';
        entities["Oacute"] = '\u00D3';
        entities["Ocirc"] = '\u00D4';
        entities["Otilde"] = '\u00D5';
        entities["Ouml"] = '\u00D6';
        entities["times"] = '\u00D7';
        entities["Oslash"] = '\u00D8';
        entities["Ugrave"] = '\u00D9';
        entities["Uacute"] = '\u00DA';
        entities["Ucirc"] = '\u00DB';
        entities["Uuml"] = '\u00DC';
        entities["Yacute"] = '\u00DD';
        entities["THORN"] = '\u00DE';
        entities["szlig"] = '\u00DF';
        entities["agrave"] = '\u00E0';
        entities["aacute"] = '\u00E1';
        entities["acirc"] = '\u00E2';
        entities["atilde"] = '\u00E3';
        entities["auml"] = '\u00E4';
        entities["aring"] = '\u00E5';
        entities["aelig"] = '\u00E6';
        entities["ccedil"] = '\u00E7';
        entities["egrave"] = '\u00E8';
        entities["eacute"] = '\u00E9';
        entities["ecirc"] = '\u00EA';
        entities["euml"] = '\u00EB';
        entities["igrave"] = '\u00EC';
        entities["iacute"] = '\u00ED';
        entities["icirc"] = '\u00EE';
        entities["iuml"] = '\u00EF';
        entities["eth"] = '\u00F0';
        entities["ntilde"] = '\u00F1';
        entities["ograve"] = '\u00F2';
        entities["oacute"] = '\u00F3';
        entities["ocirc"] = '\u00F4';
        entities["otilde"] = '\u00F5';
        entities["ouml"] = '\u00F6';
        entities["divide"] = '\u00F7';
        entities["oslash"] = '\u00F8';
        entities["ugrave"] = '\u00F9';
        entities["uacute"] = '\u00FA';
        entities["ucirc"] = '\u00FB';
        entities["uuml"] = '\u00FC';
        entities["yacute"] = '\u00FD';
        entities["thorn"] = '\u00FE';
        entities["yuml"] = '\u00FF';
        entities["fnof"] = '\u0192';
        entities["Alpha"] = '\u0391';
        entities["Beta"] = '\u0392';
        entities["Gamma"] = '\u0393';
        entities["Delta"] = '\u0394';
        entities["Epsilon"] = '\u0395';
        entities["Zeta"] = '\u0396';
        entities["Eta"] = '\u0397';
        entities["Theta"] = '\u0398';
        entities["Iota"] = '\u0399';
        entities["Kappa"] = '\u039A';
        entities["Lambda"] = '\u039B';
        entities["Mu"] = '\u039C';
        entities["Nu"] = '\u039D';
        entities["Xi"] = '\u039E';
        entities["Omicron"] = '\u039F';
        entities["Pi"] = '\u03A0';
        entities["Rho"] = '\u03A1';
        entities["Sigma"] = '\u03A3';
        entities["Tau"] = '\u03A4';
        entities["Upsilon"] = '\u03A5';
        entities["Phi"] = '\u03A6';
        entities["Chi"] = '\u03A7';
        entities["Psi"] = '\u03A8';
        entities["Omega"] = '\u03A9';
        entities["alpha"] = '\u03B1';
        entities["beta"] = '\u03B2';
        entities["gamma"] = '\u03B3';
        entities["delta"] = '\u03B4';
        entities["epsilon"] = '\u03B5';
        entities["zeta"] = '\u03B6';
        entities["eta"] = '\u03B7';
        entities["theta"] = '\u03B8';
        entities["iota"] = '\u03B9';
        entities["kappa"] = '\u03BA';
        entities["lambda"] = '\u03BB';
        entities["mu"] = '\u03BC';
        entities["nu"] = '\u03BD';
        entities["xi"] = '\u03BE';
        entities["omicron"] = '\u03BF';
        entities["pi"] = '\u03C0';
        entities["rho"] = '\u03C1';
        entities["sigmaf"] = '\u03C2';
        entities["sigma"] = '\u03C3';
        entities["tau"] = '\u03C4';
        entities["upsilon"] = '\u03C5';
        entities["phi"] = '\u03C6';
        entities["chi"] = '\u03C7';
        entities["psi"] = '\u03C8';
        entities["omega"] = '\u03C9';
        entities["thetasym"] = '\u03D1';
        entities["upsih"] = '\u03D2';
        entities["piv"] = '\u03D6';
        entities["bull"] = '\u2022';
        entities["hellip"] = '\u2026';
        entities["prime"] = '\u2032';
        entities["Prime"] = '\u2033';
        entities["oline"] = '\u203E';
        entities["frasl"] = '\u2044';
        entities["weierp"] = '\u2118';
        entities["image"] = '\u2111';
        entities["real"] = '\u211C';
        entities["trade"] = '\u2122';
        entities["alefsym"] = '\u2135';
        entities["larr"] = '\u2190';
        entities["uarr"] = '\u2191';
        entities["rarr"] = '\u2192';
        entities["darr"] = '\u2193';
        entities["harr"] = '\u2194';
        entities["crarr"] = '\u21B5';
        entities["lArr"] = '\u21D0';
        entities["uArr"] = '\u21D1';
        entities["rArr"] = '\u21D2';
        entities["dArr"] = '\u21D3';
        entities["hArr"] = '\u21D4';
        entities["forall"] = '\u2200';
        entities["part"] = '\u2202';
        entities["exist"] = '\u2203';
        entities["empty"] = '\u2205';
        entities["nabla"] = '\u2207';
        entities["isin"] = '\u2208';
        entities["notin"] = '\u2209';
        entities["ni"] = '\u220B';
        entities["prod"] = '\u220F';
        entities["sum"] = '\u2211';
        entities["minus"] = '\u2212';
        entities["lowast"] = '\u2217';
        entities["radic"] = '\u221A';
        entities["prop"] = '\u221D';
        entities["infin"] = '\u221E';
        entities["ang"] = '\u2220';
        entities["and"] = '\u2227';
        entities["or"] = '\u2228';
        entities["cap"] = '\u2229';
        entities["cup"] = '\u222A';
        entities["int"] = '\u222B';
        entities["there4"] = '\u2234';
        entities["sim"] = '\u223C';
        entities["cong"] = '\u2245';
        entities["asymp"] = '\u2248';
        entities["ne"] = '\u2260';
        entities["equiv"] = '\u2261';
        entities["le"] = '\u2264';
        entities["ge"] = '\u2265';
        entities["sub"] = '\u2282';
        entities["sup"] = '\u2283';
        entities["nsub"] = '\u2284';
        entities["sube"] = '\u2286';
        entities["supe"] = '\u2287';
        entities["oplus"] = '\u2295';
        entities["otimes"] = '\u2297';
        entities["perp"] = '\u22A5';
        entities["sdot"] = '\u22C5';
        entities["lceil"] = '\u2308';
        entities["rceil"] = '\u2309';
        entities["lfloor"] = '\u230A';
        entities["rfloor"] = '\u230B';
        entities["lang"] = '\u2329';
        entities["rang"] = '\u232A';
        entities["loz"] = '\u25CA';
        entities["spades"] = '\u2660';
        entities["clubs"] = '\u2663';
        entities["hearts"] = '\u2665';
        entities["diams"] = '\u2666';
        entities["quot"] = '\u0022';
        entities["amp"] = '\u0026';
        entities["lt"] = '\u003C';
        entities["gt"] = '\u003E';
        entities["OElig"] = '\u0152';
        entities["oelig"] = '\u0153';
        entities["Scaron"] = '\u0160';
        entities["scaron"] = '\u0161';
        entities["Yuml"] = '\u0178';
        entities["circ"] = '\u02C6';
        entities["tilde"] = '\u02DC';
        entities["ensp"] = '\u2002';
        entities["emsp"] = '\u2003';
        entities["thinsp"] = '\u2009';
        entities["zwnj"] = '\u200C';
        entities["zwj"] = '\u200D';
        entities["lrm"] = '\u200E';
        entities["rlm"] = '\u200F';
        entities["ndash"] = '\u2013';
        entities["mdash"] = '\u2014';
        entities["lsquo"] = '\u2018';
        entities["rsquo"] = '\u2019';
        entities["sbquo"] = '\u201A';
        entities["ldquo"] = '\u201C';
        entities["rdquo"] = '\u201D';
        entities["bdquo"] = '\u201E';
        entities["dagger"] = '\u2020';
        entities["Dagger"] = '\u2021';
        entities["permil"] = '\u2030';
        entities["lsaquo"] = '\u2039';
        entities["rsaquo"] = '\u203A';
        entities["euro"] = '\u20AC';
        return entities;
    }
    var Entities = initEntities();
    var rawEntity = [];
    var entity = [];
    var output = [];
    var len = s.length;
    var state = 0;
    var number = 0;
    var is_hex_value = false;
    var have_trailing_digits = false;
    for (var i = 0; i < len; i++) {
        var c = s[i];
        if (state == 0) {
            if (c == '&') {
                entity.push(c);
                rawEntity.push(c);
                state = 1;
            }
            else {
                output.push(c);
            }
            continue;
        }
        if (c == '&') {
            state = 1;
            if (have_trailing_digits) {
                entity.push(number.toString());
                have_trailing_digits = false;
            }
            output.push(entity.join(""));
            entity = [];
            entity.push('&');
            continue;
        }
        if (state == 1) {
            if (c == ';') {
                state = 0;
                output.push(entity.join(""));
                output.push(c);
                entity = [];
            }
            else {
                number = 0;
                is_hex_value = false;
                if (c != '#') {
                    state = 2;
                }
                else {
                    state = 3;
                }
                entity.push(c);
                rawEntity.push(c);
            }
        }
        else if (state == 2) {
            entity.push(c);
            if (c == ';') {
                var key = entity.join("");
                if (key.length > 1 && Entities.hasOwnProperty(key.substr(1, key.length - 2)))
                    key = Entities[key.substr(1, key.length - 2)].toString();
                output.push(key);
                state = 0;
                entity = [];
                rawEntity = [];
            }
        }
        else if (state == 3) {
            if (c == ';') {
                if (number == 0)
                    output.push(rawEntity.join("") + ";");
                else if (number > 65535) {
                    output.push("&#");
                    output.push(number.toString());
                    output.push(";");
                }
                else {
                    output.push(String.fromCharCode(number));
                }
                state = 0;
                entity = [];
                rawEntity = [];
                have_trailing_digits = false;
            }
            else if (is_hex_value && isHexDigit(c)) {
                number = number * 16 + parseInt(c, 16);
                have_trailing_digits = true;
                rawEntity.push(c);
            }
            else if (isDigit(c)) {
                number = number * 10 + (c.charCodeAt(0) - '0'.charCodeAt(0));
                have_trailing_digits = true;
                rawEntity.push(c);
            }
            else if (number == 0 && (c == 'x' || c == 'X')) {
                is_hex_value = true;
                rawEntity.push(c);
            }
            else {
                state = 2;
                if (have_trailing_digits) {
                    entity.push(number.toString());
                    have_trailing_digits = false;
                }
                entity.push(c);
            }
        }
    }
    if (entity.length > 0) {
        output.push(entity.join(""));
    }
    else if (have_trailing_digits) {
        output.push(number.toString());
    }
    return output.join("");
}
function htmlEncode(s) {
    if (s == null)
        return null;
    if (s.length == 0)
        return s;
    var needEncode = false;
    for (var i = 0; i < s.length; i++) {
        var c = s[i];
        if (c == '&' || c == '"' || c == '<' || c == '>' || c.charCodeAt(0) > 159
            || c == '\'') {
            needEncode = true;
            break;
        }
    }
    if (!needEncode)
        return s;
    var output = [];
    var len = s.length;
    for (var i = 0; i < len; i++) {
        var ch = s[i];
        switch (ch) {
            case '&':
                output.push("&amp;");
                break;
            case '>':
                output.push("&gt;");
                break;
            case '<':
                output.push("&lt;");
                break;
            case '"':
                output.push("&quot;");
                break;
            case '\'':
                output.push("&#39;");
                break;
            case '\uff1c':
                output.push("&#65308;");
                break;
            case '\uff1e':
                output.push("&#65310;");
                break;
            default:
                if (ch.charCodeAt(0) > 159 && ch.charCodeAt(0) < 256) {
                    output.push("&#");
                    output.push(ch.charCodeAt(0).toString());
                    output.push(";");
                }
                else
                    output.push(ch);
                break;
        }
    }
    return output.join("");
}

其他回答

Necromancing。 这当然不需要jQuery ! 下面是来自System.Web.HttpUtility的JavaScript端口(c# -免责声明:没有经过很好的测试):

"use strict";
function htmlDecode(s) {
    if (s == null)
        return null;
    if (s.length == 0)
        return "";
    if (s.indexOf('&') == -1)
        return s;
    function isDigit(str) {
        return /^\d+$/.test(str);
    }
    function isHexDigit(str) {
        return /[0-9A-Fa-f]{6}/g.test(str);
    }
    function initEntities() {
        var entities = {};
        entities["nbsp"] = '\u00A0';
        entities["iexcl"] = '\u00A1';
        entities["cent"] = '\u00A2';
        entities["pound"] = '\u00A3';
        entities["curren"] = '\u00A4';
        entities["yen"] = '\u00A5';
        entities["brvbar"] = '\u00A6';
        entities["sect"] = '\u00A7';
        entities["uml"] = '\u00A8';
        entities["copy"] = '\u00A9';
        entities["ordf"] = '\u00AA';
        entities["laquo"] = '\u00AB';
        entities["not"] = '\u00AC';
        entities["shy"] = '\u00AD';
        entities["reg"] = '\u00AE';
        entities["macr"] = '\u00AF';
        entities["deg"] = '\u00B0';
        entities["plusmn"] = '\u00B1';
        entities["sup2"] = '\u00B2';
        entities["sup3"] = '\u00B3';
        entities["acute"] = '\u00B4';
        entities["micro"] = '\u00B5';
        entities["para"] = '\u00B6';
        entities["middot"] = '\u00B7';
        entities["cedil"] = '\u00B8';
        entities["sup1"] = '\u00B9';
        entities["ordm"] = '\u00BA';
        entities["raquo"] = '\u00BB';
        entities["frac14"] = '\u00BC';
        entities["frac12"] = '\u00BD';
        entities["frac34"] = '\u00BE';
        entities["iquest"] = '\u00BF';
        entities["Agrave"] = '\u00C0';
        entities["Aacute"] = '\u00C1';
        entities["Acirc"] = '\u00C2';
        entities["Atilde"] = '\u00C3';
        entities["Auml"] = '\u00C4';
        entities["Aring"] = '\u00C5';
        entities["AElig"] = '\u00C6';
        entities["Ccedil"] = '\u00C7';
        entities["Egrave"] = '\u00C8';
        entities["Eacute"] = '\u00C9';
        entities["Ecirc"] = '\u00CA';
        entities["Euml"] = '\u00CB';
        entities["Igrave"] = '\u00CC';
        entities["Iacute"] = '\u00CD';
        entities["Icirc"] = '\u00CE';
        entities["Iuml"] = '\u00CF';
        entities["ETH"] = '\u00D0';
        entities["Ntilde"] = '\u00D1';
        entities["Ograve"] = '\u00D2';
        entities["Oacute"] = '\u00D3';
        entities["Ocirc"] = '\u00D4';
        entities["Otilde"] = '\u00D5';
        entities["Ouml"] = '\u00D6';
        entities["times"] = '\u00D7';
        entities["Oslash"] = '\u00D8';
        entities["Ugrave"] = '\u00D9';
        entities["Uacute"] = '\u00DA';
        entities["Ucirc"] = '\u00DB';
        entities["Uuml"] = '\u00DC';
        entities["Yacute"] = '\u00DD';
        entities["THORN"] = '\u00DE';
        entities["szlig"] = '\u00DF';
        entities["agrave"] = '\u00E0';
        entities["aacute"] = '\u00E1';
        entities["acirc"] = '\u00E2';
        entities["atilde"] = '\u00E3';
        entities["auml"] = '\u00E4';
        entities["aring"] = '\u00E5';
        entities["aelig"] = '\u00E6';
        entities["ccedil"] = '\u00E7';
        entities["egrave"] = '\u00E8';
        entities["eacute"] = '\u00E9';
        entities["ecirc"] = '\u00EA';
        entities["euml"] = '\u00EB';
        entities["igrave"] = '\u00EC';
        entities["iacute"] = '\u00ED';
        entities["icirc"] = '\u00EE';
        entities["iuml"] = '\u00EF';
        entities["eth"] = '\u00F0';
        entities["ntilde"] = '\u00F1';
        entities["ograve"] = '\u00F2';
        entities["oacute"] = '\u00F3';
        entities["ocirc"] = '\u00F4';
        entities["otilde"] = '\u00F5';
        entities["ouml"] = '\u00F6';
        entities["divide"] = '\u00F7';
        entities["oslash"] = '\u00F8';
        entities["ugrave"] = '\u00F9';
        entities["uacute"] = '\u00FA';
        entities["ucirc"] = '\u00FB';
        entities["uuml"] = '\u00FC';
        entities["yacute"] = '\u00FD';
        entities["thorn"] = '\u00FE';
        entities["yuml"] = '\u00FF';
        entities["fnof"] = '\u0192';
        entities["Alpha"] = '\u0391';
        entities["Beta"] = '\u0392';
        entities["Gamma"] = '\u0393';
        entities["Delta"] = '\u0394';
        entities["Epsilon"] = '\u0395';
        entities["Zeta"] = '\u0396';
        entities["Eta"] = '\u0397';
        entities["Theta"] = '\u0398';
        entities["Iota"] = '\u0399';
        entities["Kappa"] = '\u039A';
        entities["Lambda"] = '\u039B';
        entities["Mu"] = '\u039C';
        entities["Nu"] = '\u039D';
        entities["Xi"] = '\u039E';
        entities["Omicron"] = '\u039F';
        entities["Pi"] = '\u03A0';
        entities["Rho"] = '\u03A1';
        entities["Sigma"] = '\u03A3';
        entities["Tau"] = '\u03A4';
        entities["Upsilon"] = '\u03A5';
        entities["Phi"] = '\u03A6';
        entities["Chi"] = '\u03A7';
        entities["Psi"] = '\u03A8';
        entities["Omega"] = '\u03A9';
        entities["alpha"] = '\u03B1';
        entities["beta"] = '\u03B2';
        entities["gamma"] = '\u03B3';
        entities["delta"] = '\u03B4';
        entities["epsilon"] = '\u03B5';
        entities["zeta"] = '\u03B6';
        entities["eta"] = '\u03B7';
        entities["theta"] = '\u03B8';
        entities["iota"] = '\u03B9';
        entities["kappa"] = '\u03BA';
        entities["lambda"] = '\u03BB';
        entities["mu"] = '\u03BC';
        entities["nu"] = '\u03BD';
        entities["xi"] = '\u03BE';
        entities["omicron"] = '\u03BF';
        entities["pi"] = '\u03C0';
        entities["rho"] = '\u03C1';
        entities["sigmaf"] = '\u03C2';
        entities["sigma"] = '\u03C3';
        entities["tau"] = '\u03C4';
        entities["upsilon"] = '\u03C5';
        entities["phi"] = '\u03C6';
        entities["chi"] = '\u03C7';
        entities["psi"] = '\u03C8';
        entities["omega"] = '\u03C9';
        entities["thetasym"] = '\u03D1';
        entities["upsih"] = '\u03D2';
        entities["piv"] = '\u03D6';
        entities["bull"] = '\u2022';
        entities["hellip"] = '\u2026';
        entities["prime"] = '\u2032';
        entities["Prime"] = '\u2033';
        entities["oline"] = '\u203E';
        entities["frasl"] = '\u2044';
        entities["weierp"] = '\u2118';
        entities["image"] = '\u2111';
        entities["real"] = '\u211C';
        entities["trade"] = '\u2122';
        entities["alefsym"] = '\u2135';
        entities["larr"] = '\u2190';
        entities["uarr"] = '\u2191';
        entities["rarr"] = '\u2192';
        entities["darr"] = '\u2193';
        entities["harr"] = '\u2194';
        entities["crarr"] = '\u21B5';
        entities["lArr"] = '\u21D0';
        entities["uArr"] = '\u21D1';
        entities["rArr"] = '\u21D2';
        entities["dArr"] = '\u21D3';
        entities["hArr"] = '\u21D4';
        entities["forall"] = '\u2200';
        entities["part"] = '\u2202';
        entities["exist"] = '\u2203';
        entities["empty"] = '\u2205';
        entities["nabla"] = '\u2207';
        entities["isin"] = '\u2208';
        entities["notin"] = '\u2209';
        entities["ni"] = '\u220B';
        entities["prod"] = '\u220F';
        entities["sum"] = '\u2211';
        entities["minus"] = '\u2212';
        entities["lowast"] = '\u2217';
        entities["radic"] = '\u221A';
        entities["prop"] = '\u221D';
        entities["infin"] = '\u221E';
        entities["ang"] = '\u2220';
        entities["and"] = '\u2227';
        entities["or"] = '\u2228';
        entities["cap"] = '\u2229';
        entities["cup"] = '\u222A';
        entities["int"] = '\u222B';
        entities["there4"] = '\u2234';
        entities["sim"] = '\u223C';
        entities["cong"] = '\u2245';
        entities["asymp"] = '\u2248';
        entities["ne"] = '\u2260';
        entities["equiv"] = '\u2261';
        entities["le"] = '\u2264';
        entities["ge"] = '\u2265';
        entities["sub"] = '\u2282';
        entities["sup"] = '\u2283';
        entities["nsub"] = '\u2284';
        entities["sube"] = '\u2286';
        entities["supe"] = '\u2287';
        entities["oplus"] = '\u2295';
        entities["otimes"] = '\u2297';
        entities["perp"] = '\u22A5';
        entities["sdot"] = '\u22C5';
        entities["lceil"] = '\u2308';
        entities["rceil"] = '\u2309';
        entities["lfloor"] = '\u230A';
        entities["rfloor"] = '\u230B';
        entities["lang"] = '\u2329';
        entities["rang"] = '\u232A';
        entities["loz"] = '\u25CA';
        entities["spades"] = '\u2660';
        entities["clubs"] = '\u2663';
        entities["hearts"] = '\u2665';
        entities["diams"] = '\u2666';
        entities["quot"] = '\u0022';
        entities["amp"] = '\u0026';
        entities["lt"] = '\u003C';
        entities["gt"] = '\u003E';
        entities["OElig"] = '\u0152';
        entities["oelig"] = '\u0153';
        entities["Scaron"] = '\u0160';
        entities["scaron"] = '\u0161';
        entities["Yuml"] = '\u0178';
        entities["circ"] = '\u02C6';
        entities["tilde"] = '\u02DC';
        entities["ensp"] = '\u2002';
        entities["emsp"] = '\u2003';
        entities["thinsp"] = '\u2009';
        entities["zwnj"] = '\u200C';
        entities["zwj"] = '\u200D';
        entities["lrm"] = '\u200E';
        entities["rlm"] = '\u200F';
        entities["ndash"] = '\u2013';
        entities["mdash"] = '\u2014';
        entities["lsquo"] = '\u2018';
        entities["rsquo"] = '\u2019';
        entities["sbquo"] = '\u201A';
        entities["ldquo"] = '\u201C';
        entities["rdquo"] = '\u201D';
        entities["bdquo"] = '\u201E';
        entities["dagger"] = '\u2020';
        entities["Dagger"] = '\u2021';
        entities["permil"] = '\u2030';
        entities["lsaquo"] = '\u2039';
        entities["rsaquo"] = '\u203A';
        entities["euro"] = '\u20AC';
        return entities;
    }
    var Entities = initEntities();
    var rawEntity = [];
    var entity = [];
    var output = [];
    var len = s.length;
    var state = 0;
    var number = 0;
    var is_hex_value = false;
    var have_trailing_digits = false;
    for (var i = 0; i < len; i++) {
        var c = s[i];
        if (state == 0) {
            if (c == '&') {
                entity.push(c);
                rawEntity.push(c);
                state = 1;
            }
            else {
                output.push(c);
            }
            continue;
        }
        if (c == '&') {
            state = 1;
            if (have_trailing_digits) {
                entity.push(number.toString());
                have_trailing_digits = false;
            }
            output.push(entity.join(""));
            entity = [];
            entity.push('&');
            continue;
        }
        if (state == 1) {
            if (c == ';') {
                state = 0;
                output.push(entity.join(""));
                output.push(c);
                entity = [];
            }
            else {
                number = 0;
                is_hex_value = false;
                if (c != '#') {
                    state = 2;
                }
                else {
                    state = 3;
                }
                entity.push(c);
                rawEntity.push(c);
            }
        }
        else if (state == 2) {
            entity.push(c);
            if (c == ';') {
                var key = entity.join("");
                if (key.length > 1 && Entities.hasOwnProperty(key.substr(1, key.length - 2)))
                    key = Entities[key.substr(1, key.length - 2)].toString();
                output.push(key);
                state = 0;
                entity = [];
                rawEntity = [];
            }
        }
        else if (state == 3) {
            if (c == ';') {
                if (number == 0)
                    output.push(rawEntity.join("") + ";");
                else if (number > 65535) {
                    output.push("&#");
                    output.push(number.toString());
                    output.push(";");
                }
                else {
                    output.push(String.fromCharCode(number));
                }
                state = 0;
                entity = [];
                rawEntity = [];
                have_trailing_digits = false;
            }
            else if (is_hex_value && isHexDigit(c)) {
                number = number * 16 + parseInt(c, 16);
                have_trailing_digits = true;
                rawEntity.push(c);
            }
            else if (isDigit(c)) {
                number = number * 10 + (c.charCodeAt(0) - '0'.charCodeAt(0));
                have_trailing_digits = true;
                rawEntity.push(c);
            }
            else if (number == 0 && (c == 'x' || c == 'X')) {
                is_hex_value = true;
                rawEntity.push(c);
            }
            else {
                state = 2;
                if (have_trailing_digits) {
                    entity.push(number.toString());
                    have_trailing_digits = false;
                }
                entity.push(c);
            }
        }
    }
    if (entity.length > 0) {
        output.push(entity.join(""));
    }
    else if (have_trailing_digits) {
        output.push(number.toString());
    }
    return output.join("");
}
function htmlEncode(s) {
    if (s == null)
        return null;
    if (s.length == 0)
        return s;
    var needEncode = false;
    for (var i = 0; i < s.length; i++) {
        var c = s[i];
        if (c == '&' || c == '"' || c == '<' || c == '>' || c.charCodeAt(0) > 159
            || c == '\'') {
            needEncode = true;
            break;
        }
    }
    if (!needEncode)
        return s;
    var output = [];
    var len = s.length;
    for (var i = 0; i < len; i++) {
        var ch = s[i];
        switch (ch) {
            case '&':
                output.push("&amp;");
                break;
            case '>':
                output.push("&gt;");
                break;
            case '<':
                output.push("&lt;");
                break;
            case '"':
                output.push("&quot;");
                break;
            case '\'':
                output.push("&#39;");
                break;
            case '\uff1c':
                output.push("&#65308;");
                break;
            case '\uff1e':
                output.push("&#65310;");
                break;
            default:
                if (ch.charCodeAt(0) > 159 && ch.charCodeAt(0) < 256) {
                    output.push("&#");
                    output.push(ch.charCodeAt(0).toString());
                    output.push(";");
                }
                else
                    output.push(ch);
                break;
        }
    }
    return output.join("");
}

您不应该为了将值从一个输入字段转移到另一个输入字段而对值进行转义/编码。

<form>
 <input id="button" type="button" value="Click me">
 <input type="hidden" id="hiddenId" name="hiddenId" value="I like cheese">
 <input type="text" id="output" name="output">
</form>
<script>
    $(document).ready(function(e) {
        $('#button').click(function(e) {
            $('#output').val($('#hiddenId').val());
        });
    });
</script>

JS不会插入原始HTML或其他东西;它只是告诉DOM设置value属性(或属性;不确定)。无论哪种方式,DOM都可以为您处理任何编码问题。除非你在做一些奇怪的事情,比如使用document。写或eval, html编码将是有效透明的。

如果你正在讨论生成一个新的文本框来保存结果……还是那么简单。只需要将HTML的静态部分传递给jQuery,然后设置它返回给你的对象的其余属性/属性。

$box = $('<input type="text" name="whatever">').val($('#hiddenId').val());
<script>
String.prototype.htmlEncode = function () {
    return String(this)
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');

}

var aString = '<script>alert("I hack your site")</script>';
console.log(aString.htmlEncode());
</script>

将输出:&lt;script&gt;alert(&quot;I hack your site&quot;)&lt;/script&gt;

. htmlencode()一旦定义,就可以在所有字符串上访问。

jQuery的技巧不编码引号,在IE中它会删除你的空白。

基于Django中的escape templatetag,我猜它已经被大量使用/测试过了,我做了这个函数来做需要的事情。

可以说,它比解决空格剥离问题的任何变通方法都更简单(而且可能更快)——而且它对引号进行了编码,例如,如果您打算在属性值中使用结果,那么引号是必不可少的。

function htmlEscape(str) {
    return str
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

// I needed the opposite function today, so adding here too:
function htmlUnescape(str){
    return str
        .replace(/&quot;/g, '"')
        .replace(/&#39;/g, "'")
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&');
}

更新2013-06-17: 在寻找最快的转义,我发现了一个replaceAll方法的实现: http://dumpsite.com/forum/index.php?topic=4.msg29#msg29 (这里也引用了:替换字符串中所有字符实例的最快方法) 下面是一些性能结果: http://jsperf.com/htmlencoderegex/25

它给出了与上面的内置替换链相同的结果字符串。如果有人能解释为什么它更快,我会很高兴!?

更新2015-03-04: 我刚刚注意到AngularJS正在使用上面的方法: https://github.com/angular/angular.js/blob/v1.3.14/src/ngSanitize/sanitize.js#L435

他们增加了一些改进——他们似乎在处理一个模糊的Unicode问题,以及将所有非字母数字字符转换为实体。在我的印象中,后者是不需要的,只要您为您的文档指定了UTF8字符集。

我要指出的是,(4年后)Django仍然没有做这些事情,所以我不确定它们有多重要: https://github.com/django/django/blob/1.8b1/django/utils/html.py#L44

更新2016-04-06: 你也可能希望转义正斜杠/。对于正确的HTML编码,这不是必需的,但是OWASP建议将其作为一种抗xss安全措施。(感谢@JNF在评论中提出这个建议)

        .replace(/\//g, '&#x2F;');

这是一个简单的javascript解决方案。它通过“HTMLEncode”方法扩展String对象,该方法可以用于不带参数的对象,也可以用于带参数的对象。

String.prototype.HTMLEncode = function(str) {
  var result = "";
  var str = (arguments.length===1) ? str : this;
  for(var i=0; i<str.length; i++) {
     var chrcode = str.charCodeAt(i);
     result+=(chrcode>128) ? "&#"+chrcode+";" : str.substr(i,1)
   }
   return result;
}
// TEST
console.log("stetaewteaw æø".HTMLEncode());
console.log("stetaewteaw æø".HTMLEncode("æåøåæå"))

我已经做了一个主旨“HTMLEncode方法javascript”。