【问题标题】:Convert special characters to HTML in JavaScriptConvert special characters to HTML in JavaScript
【发布时间】:2022-03-26 20:27:49
【问题描述】:

How can I convert special characters to HTML in JavaScript?

Example:

  • & (ampersand) becomes &amp.
  • " (double quote) becomes &quot when ENT_NOQUOTES is not set.
  • ' (single quote) becomes &#039 only when ENT_QUOTES is set.
  • < (less than) becomes &lt.
  • > (greater than) becomes &gt.

【问题讨论】:

标签: javascript


【解决方案1】:

The best way in my opinion is to use the browser's inbuilt HTML escape functionality to handle many of the cases. To do this simply create a element in the DOM tree and set the innerText of the element to your string. Then retrieve the innerHTML of the element. The browser will return an HTML encoded string.

function HtmlEncode(s)
{
  var el = document.createElement("div");
  el.innerText = el.textContent = s;
  s = el.innerHTML;
  return s;
}

Test run:

alert(HtmlEncode('&;'><"'));

Output:

&amp;;'&gt;&lt;"

This method of escaping HTML is also used by the Prototype JS library though differently from the simplistic sample I have given.

Note: You will still need to escape quotes (double and single) yourself. You can use any of the methods outlined by others here.

【讨论】:

  • note that delete el is a mistake here. perfectionkills.com/understanding-delete
  • 当我尝试时,这对我没有任何作用。我得到的字符不变。
  • 抱歉,我正在测试奇怪的字符,而且 Chrome 是偷偷摸摸的,不会向您显示真正的 HTML 输出,但 Firebug 会显示(实际上,当生成的源未对其进行编码时,它会显示版权符号的 html 实体)。这在 &lt;&gt;&amp; 上运行良好,但不像 Neotropic 或 KooiInc 的解决方案那样包罗万象。
  • 使用 jQuery,output = $('&lt;div&gt;').text(input).html()
  • 这两种方法都不会将 ' 转换为 ';而“入”,所以还是可以用来进行XSS攻击的。
【解决方案2】:

你需要一个函数来做类似的事情

return mystring.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");

但考虑到您希望对单引号/双引号进行不同的处理。

【讨论】:

  • 斜线 g 有什么作用?
  • @JohnnyBizzle /g 在正则表达式中表示“全局”。简而言之,所有出现的字符串都将被替换。如果没有/g,只会替换第一个匹配项。
【解决方案3】:

对于那些想要解码字符串中的整数字符代码,如 &amp;#xxx;,请使用此函数:

function decodeHtmlCharCodes(str) { 
  return str.replace(/(&#(d+);)/g, function(match, capture, charCode) {
    return String.fromCharCode(charCode);
  });
}

// Will output "The show that gained int’l reputation’!"
console.log(decodeHtmlCharCodes('The show that gained int&#8217;l reputation&#8217;!'));

ES6

const decodeHtmlCharCodes = str => 
  str.replace(/(&#(d+);)/g, (match, capture, charCode) => 
    String.fromCharCode(charCode));

// Will output "The show that gained int’l reputation’!"
console.log(decodeHtmlCharCodes('The show that gained int&#8217;l reputation&#8217;!'));

【讨论】:

  • 这应该是公认的答案,因为这将解码所有内容。
  • 请注意,这仅解码整数字符代码。它不会解码像 & 这样的东西。或
  • @Magmatic 的开场白“对于那些想要在字符串中解码像&amp;#xxx;这样的整数字符代码的人" 足够清楚地表明这些函数是用于解码的整数编码;如果你想解码命名的编码,这里还有很多其他函数可以做到这一点。
【解决方案4】:

这个通用函数将每个非字母字符编码为其 HTML 代码 (numeric character reference (NCR)):

function HTMLEncode(str) {
    var i = str.length,
        aRet = [];

    while (i--) {
        var iC = str[i].charCodeAt();
        if (iC < 65 || iC > 127 || (iC>90 && iC<97)) {
            aRet[i] = '&#'+iC+';';
        } else {
            aRet[i] = str[i];
        }
    }
    return aRet.join('');
}

[编辑 2022] 更现代的方法:

const toHtmlEntities = (str, showInHtml = false) => 
  [...str].map( v => `${showInHtml ? `&amp;#` : `&#`}${v.charCodeAt(0)};`).join(``);
const str = `&Hellõ Wórld`;

document.body.insertAdjacentHTML(`beforeend`, `<ul>
  <li>Show the entities (<code>toHtmlEntities(str, true)</code>): <b>${
    toHtmlEntities(str, true)}</b></li>
  <li>Let the browser decide (<code>toHtmlEntities(str)</code>): <b>${
    toHtmlEntities(str)}</b></li>
  <li id="textOnly"></li></ul>`);
document.querySelector(`#textOnly`).textContent = `As textContent: ${
  toHtmlEntities(str)}`;
body {
  font: 14px / 18px "normal verdana", arial;
  margin: 1rem;
}

code {
  background-color: #eee;
}

【讨论】:

  • 这听起来真的很聪明,但我只能用它来转换基础知识:&lt;&gt;&amp;
  • nvm。它在控制台中运行良好,但是当您输出到浏览器时,它看起来好像没有转换内容。这是怎么回事?
  • @Moss:浏览器将 html 编码的字符呈现为它们所代表的字符。 html 编码字符的优点是浏览器不必猜测(例如)变音字符的翻译,因此总是按照应呈现的方式呈现这些字符。
  • 您可能会考虑更改此设置以删除 str 的类似数组的访问。 IE7 及更低版本不支持该功能,并且您可以使用 i 作为参数轻松调用 str 的 charCodeAt。 var iC = str.charCodeAt(i)
  • 此代码没有为应该为 ± 的 ± 字符生成正确的 HTML 实体值。但它正在返回 �这是一个未知字符 �。
【解决方案5】:

创建一个使用字符串replace的函数

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

【讨论】:

  • 我的输入值中只有单引号 (') 和双引号 (") 显示在 html 中时遇到问题。如果用户添加脚本,脚本就会中断。
【解决方案6】:

来自 Mozilla ...

请注意,charCodeAt 将始终返回一个小于 65,536 的值。这是因为较高的代码点由一对(较低值的)“代理”伪字符表示,这些伪字符用于构成真实字符。因此,为了检查或再现值 65,536 及以上的单个字符的完整字符,对于此类字符,不仅需要检索 charCodeAt(i),还需要检索 charCodeAt(i+1)(就像检查/ 用两个 > 字母生成一个字符串)。

最佳解决方案

/**
 * (c) 2012 Steven Levithan <http://slevithan.com/>
 * MIT license
 */
if (!String.prototype.codePointAt) {
    String.prototype.codePointAt = function (pos) {
        pos = isNaN(pos) ? 0 : pos;
        var str = String(this),
            code = str.charCodeAt(pos),
            next = str.charCodeAt(pos + 1);
        // If a surrogate pair
        if (0xD800 <= code && code <= 0xDBFF && 0xDC00 <= next && next <= 0xDFFF) {
            return ((code - 0xD800) * 0x400) + (next - 0xDC00) + 0x10000;
        }
        return code;
    };
}

/**
 * Encodes special html characters
 * @param string
 * @return {*}
 */
function html_encode(string) {
    var ret_val = '';
    for (var i = 0; i < string.length; i++) { 
        if (string.codePointAt(i) > 127) {
            ret_val += '&#' + string.codePointAt(i) + ';';
        } else {
            ret_val += string.charAt(i);
        }
    }
    return ret_val;
}

使用示例:

html_encode("✈");

【讨论】:

    【解决方案7】:

    mentioned by dragon一样,最干净的方法是使用jQuery

    function htmlEncode(s) {
        return $('<div>').text(s).html();
    }
    
    function htmlDecode(s) {
        return $('<div>').html(s).text();
    }
    

    【讨论】:

    • 有趣,但如果您的字符串包含空格,这不会改变它。更好的方法是使用 encodeURI(yourString);
    • 空格不是特殊字符。 encodeURI 用于编码 URL 而不是 HTML ...它是错误的工具。
    【解决方案8】:
    function char_convert() {
    
        var chars = ["©","Û","®","ž","Ü","Ÿ","Ý","$","Þ","%","¡","ß","¢","à","£","á","À","¤","â","Á","¥","ã","Â","¦","ä","Ã","§","å","Ä","¨","æ","Å","©","ç","Æ","ª","è","Ç","«","é","È","¬","ê","É","­","ë","Ê","®","ì","Ë","¯","í","Ì","°","î","Í","±","ï","Î","²","ð","Ï","³","ñ","Ð","´","ò","Ñ","µ","ó","Õ","¶","ô","Ö","·","õ","Ø","¸","ö","Ù","¹","÷","Ú","º","ø","Û","»","ù","Ü","@","¼","ú","Ý","½","û","Þ","€","¾","ü","ß","¿","ý","à","‚","À","þ","á","ƒ","Á","ÿ","å","„","Â","æ","…","Ã","ç","†","Ä","è","‡","Å","é","ˆ","Æ","ê","‰","Ç","ë","Š","È","ì","‹","É","í","Œ","Ê","î","Ë","ï","Ž","Ì","ð","Í","ñ","Î","ò","‘","Ï","ó","’","Ð","ô","“","Ñ","õ","”","Ò","ö","•","Ó","ø","–","Ô","ù","—","Õ","ú","˜","Ö","û","™","×","ý","š","Ø","þ","›","Ù","ÿ","œ","Ú"]; 
        var codes = ["&copy;","&#219;","&reg;","&#158;","&#220;","&#159;","&#221;","&#36;","&#222;","&#37;","&#161;","&#223;","&#162;","&#224;","&#163;","&#225;","&Agrave;","&#164;","&#226;","&Aacute;","&#165;","&#227;","&Acirc;","&#166;","&#228;","&Atilde;","&#167;","&#229;","&Auml;","&#168;","&#230;","&Aring;","&#169;","&#231;","&AElig;","&#170;","&#232;","&Ccedil;","&#171;","&#233;","&Egrave;","&#172;","&#234;","&Eacute;","&#173;","&#235;","&Ecirc;","&#174;","&#236;","&Euml;","&#175;","&#237;","&Igrave;","&#176;","&#238;","&Iacute;","&#177;","&#239;","&Icirc;","&#178;","&#240;","&Iuml;","&#179;","&#241;","&ETH;","&#180;","&#242;","&Ntilde;","&#181;","&#243;","&Otilde;","&#182;","&#244;","&Ouml;","&#183;","&#245;","&Oslash;","&#184;","&#246;","&Ugrave;","&#185;","&#247;","&Uacute;","&#186;","&#248;","&Ucirc;","&#187;","&#249;","&Uuml;","&#64;","&#188;","&#250;","&Yacute;","&#189;","&#251;","&THORN;","&#128;","&#190;","&#252","&szlig;","&#191;","&#253;","&agrave;","&#130;","&#192;","&#254;","&aacute;","&#131;","&#193;","&#255;","&aring;","&#132;","&#194;","&aelig;","&#133;","&#195;","&ccedil;","&#134;","&#196;","&egrave;","&#135;","&#197;","&eacute;","&#136;","&#198;","&ecirc;","&#137;","&#199;","&euml;","&#138;","&#200;","&igrave;","&#139;","&#201;","&iacute;","&#140;","&#202;","&icirc;","&#203;","&iuml;","&#142;","&#204;","&eth;","&#205;","&ntilde;","&#206;","&ograve;","&#145;","&#207;","&oacute;","&#146;","&#208;","&ocirc;","&#147;","&#209;","&otilde;","&#148;","&#210;","&ouml;","&#149;","&#211;","&oslash;","&#150;","&#212;","&ugrave;","&#151;","&#213;","&uacute;","&#152;","&#214;","&ucirc;","&#153;","&#215;","&yacute;","&#154;","&#216;","&thorn;","&#155;","&#217;","&yuml;","&#156;","&#218;"];
    
        for(x=0; x<chars.length; x++){
            for (i=0; i<arguments.length; i++){
                arguments[i].value = arguments[i].value.replace(chars[x], codes[x]);
            }
        }
     }
    
    char_convert(this);
    

    【讨论】:

    • 这很好用。但是由于某种原因,当与某些 JQuery 功能混合使用时,它会失败。有时确实会转换一些,或者只有几个。但总的来说,效果很好。 onBlur="char_convert(这个);"
    • 呃,我在 Chrome 中收到错误“Uncaught TypeError: Cannot call method 'replace' of undefined”,在 Firebug 中收到“arguments[i].value is undefined”。
    • 将所有这些特殊字符放入这样的数组中是完全没有意义的。查看其他答案。
    • 对我来说最好的解决方案,唯一一个将 í 转换为 í例如。
    • 你如何从键盘上获取这些字符?我知道这是一个愚蠢的问题……例如在 OS X 中
    【解决方案9】:
    function ConvChar(str) {
        c = {'&lt;':'&amp;lt;', '&gt;':'&amp;gt;', '&':'&amp;amp;',
             '"':'&amp;quot;', "'":'&amp;#039;', '#':'&amp;#035;' };
    
        return str.replace(/[&lt;&amp;>'"#]/g, function(s) { return c[s]; });
    }
    
    alert(ConvChar('&lt;-"-&-"->-&lt;-'-#-'->'));
    

    结果:

    <-"-&-"->-<-'-#-'->

    在 testarea 标签中:

    <-"-&-"->-<-'-#-'->

    如果你只是改变长代码中的几个字符......

    【讨论】:

      【解决方案10】:

      如果您需要all standardized named character referencesUnicodeambiguous ampersands 的支持,he 库是我所知道的唯一 100% 可靠的解决方案!


      使用示例

      he.encode('foo © bar ≠ baz ? qux');
      // Output: 'foo &#xA9; bar &#x2260; baz &#x1D306; qux'
      
      he.decode('foo &copy; bar &ne; baz &#x1D306; qux');
      // Output: 'foo © bar ≠ baz ? qux'
      

      【讨论】:

        【解决方案11】:

        PRE 标记中 - 以及大多数其他 HTML 标记中 - 使用输出重定向字符(&lt;&gt;)的批处理文件的纯文本将破坏 HTML,但是这是我的小费TEXTAREA 元素中的任何内容 - 它不会破坏 HTML,主要是因为我们在操作系统实例化和处理的控件中,因此它的内容不会被 HTML 引擎解析。

        例如,假设我想使用 JavaScript 突出显示我的批处理文件的语法。我只是将代码粘贴到文本区域中,而不用担心 HTML 保留字符,并让脚本处理文本区域的 innerHTML 属性,该属性计算出 HTML 保留字符替换为相应的 ISO 8859-1 实体的文本。

        当您检索元素的 innerHTML(和 outerHTML)属性时,浏览器将自动转义特殊字符。使用文本区域(谁知道呢,也许是文本类型的输入)只会让您免于进行转换(手动或通过代码)。

        我使用这个技巧来测试我的语法荧光笔,当我完成创作和测试后,我只是将文本区域从视图中隐藏起来。

        【讨论】:

          【解决方案12】:

          解决方法:

          var temp = $("div").text("<");
          var afterEscape = temp.html(); // afterEscape == "&lt;"
          

          【讨论】:

            【解决方案13】:

            这是我发现在这种情况下非常有用的一个很好的库。

            https://github.com/mathiasbynens/he

            据其作者称:

            它支持按照 HTML 的所有标准化命名字符引用, 像浏览器一样处理不明确的符号和其他边缘情况 会,有一个广泛的测试套件,并且 - 与许多其他 JavaScript 解决方案——他可以很好地处理 astral Unicode 符号

            【讨论】:

            【解决方案14】:

            利用:

            var swapCodes   = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230, 8482, 169, 61558, 8226, 61607);
            var swapStrings = new Array("--", "--", "'",  "'",  '"',  '"',  "*",  "...", "&trade;", "&copy;", "&bull;", "&bull;", "&bull;");
            
            var TextCheck = {
                doCWBind:function(div){
                    $(div).bind({
                        bind:function(){
                            TextCheck.cleanWord(div);
                        },
                        focus:function(){
                            TextCheck.cleanWord(div);
                        },
                        paste:function(){
                            TextCheck.cleanWord(div);
                        }
                    });
                },
                cleanWord:function(div){
                    var output = $(div).val();
                    for (i = 0; i < swapCodes.length; i++) {
                        var swapper = new RegExp("\u" + swapCodes[i].toString(16), "g");
                        output = output.replace(swapper, swapStrings[i]);
                    }
                    $(div).val(output);
                }
            }
            

            我们现在使用的另一个有效。上面的那个我让它调用脚本并返回转换后的代码。它只适用于小文本区域(意味着不是完整的文章、博客等)


            对于以上。它适用于大多数角色。

            var swapCodes   = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230, 8482, 61558, 8226, 61607, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 338, 339, 352, 353, 376, 402);
            var swapStrings = new Array("--", "--", "'",  "'",  '"',  '"',  "*",  "...", "&trade;", "&bull;", "&bull;", "&bull;", "&iexcl;", "&cent;", "&pound;", "&curren;", "&yen;", "&brvbar;", "&sect;", "&uml;", "&copy;", "&ordf;", "&laquo;", "&not;", "&shy;", "&reg;", "&macr;", "&deg;", "&plusmn;", "&sup2;", "&sup3;", "&acute;", "&micro;", "&para;", "&middot;", "&cedil;", "&sup1;", "&ordm;", "&raquo;", "&frac14;", "&frac12;", "&frac34;", "&iquest;", "&Agrave;", "&Aacute;", "&Acirc;", "&Atilde;", "&Auml;", "&Aring;", "&AElig;", "&Ccedil;", "&Egrave;", "&Eacute;", "&Ecirc;", "&Euml;", "&Igrave;", "&Iacute;", "&Icirc;", "&Iuml;", "&ETH;", "&Ntilde;", "&Ograve;", "&Oacute;", "&Ocirc;", "&Otilde;", "&Ouml;", "&times;", "&Oslash;", "&Ugrave;", "&Uacute;", "&Ucirc;", "&Uuml;", "&Yacute;", "&THORN;", "&szlig;", "&agrave;", "&aacute;", "&acirc;", "&atilde;", "&auml;", "&aring;", "&aelig;", "&ccedil;", "&egrave;", "&eacute;", "&ecirc;", "&euml;", "&igrave;", "&iacute;", "&icirc;", "&iuml;", "&eth;", "&ntilde;", "&ograve;", "&oacute;", "&ocirc;", "&otilde;", "&ouml;", "&divide;", "&oslash;", "&ugrave;", "&uacute;", "&ucirc;", "&uuml;", "&yacute;", "&thorn;", "&yuml;", "&#338;", "&#339;", "&#352;", "&#353;", "&#376;", "&#402;");
            

            我创建了一个具有很多功能的 javascript 文件,包括上述功能。 http://www.neotropicsolutions.com/JSChars.zip

            包括所有需要的文件。我添加了 jQuery 1.4.4。仅仅是因为我在其他版本中看到了问题,还没有尝试过。

            Requires: jQuery & jQuery Impromptu from: http://trentrichardson.com/Impromptu/index.php
            
            1. Word Count
            2. Character Conversion
            3. Checks to ensure this is not passed: "notsomeverylongstringmissingspaces"
            4. Checks to make sure ALL IS NOT ALL UPPERCASE.
            5. Strip HTML
            
                // Word Counter
                $.getScript('js/characters.js', function(){
                    $('#adtxt').bind("keyup click blur focus change paste",
                        function(event){
                            TextCheck.wordCount(30, "#adtxt", "#adtxt_count", event);
                    });
                    $('#adtxt').blur(
                        function(event){
                            TextCheck.check_length('#adtxt'); // unsures properly spaces-not one long word
                            TextCheck.doCWBind('#adtxt'); // char conversion
                    });
            
                    TextCheck.wordCount(30, "#adtxt", "#adtxt_count", false);
                });
            
                //HTML
                <textarea name="adtxt" id="adtxt" rows="10" cols="70" class="wordCount"></textarea>
            
                <div id="adtxt_count" class="clear"></div>
            
                // Just Character Conversions:
                TextCheck.doCWBind('#myfield');
            
                // Run through form fields in a form for case checking.
                // Alerts user when field is blur'd.
                var labels = new Array("Brief Description", "Website URL", "Contact Name", "Website", "Email", "Linkback URL");
                var checking = new Array("descr", "title", "fname", "website", "email", "linkback");
                TextCheck.check_it(checking, labels);
            
                // Extra security to check again, make sure form is not submitted
                var pass = TextCheck.validate(checking, labels);
                if(pass){
                    // Do form actions
                }
            
                //Strip HTML
                <textarea name="adtxt" id="adtxt" rows="10" cols="70" onblur="TextCheck.stripHTML(this);"></textarea>
            

            【讨论】:

              【解决方案15】:
              <!doctype html>
              <html lang="en">
                  <head>
                      <meta charset="utf-8">
                      <title>html</title>
              
                      <script>
                          $(function() {
                              document.getElementById('test').innerHTML = "&amp;";
                          });
                      </script>
                  </head>
              
                  <body>
                      <div id="test"></div>
                  </body>
              </html>
              

              您可以使用上面的代码简单地将特殊字符转换为 HTML。

              【讨论】:

                【解决方案16】:
                function escape (text)
                {
                  return text.replace(/[<>&"']/g, function(c) {
                    return '&#' + c.charCodeAt(0) + ';';
                  });
                }
                
                alert(escape("<>&'""));
                

                【讨论】:

                  【解决方案17】:

                  这并没有直接回答您的问题,但是如果您使用innerHTML 以便在元素中写入文本并且遇到编码问题,只需使用textContent,即:

                  var s = "Foo 'bar' baz <qux>";
                  
                  var element = document.getElementById('foo');
                  element.textContent = s;
                  
                  // <div id="foo">Foo 'bar' baz <qux></div>
                  

                  【讨论】:

                    【解决方案18】:

                    这是我在不需要 jQuery 的情况下使用的几种方法:

                    你可以编码每个字符在你的字符串中:

                    function encode(e){return e.replace(/[^]/g, function(e) {return "&#" + e.charCodeAt(0) + ";"})}
                    

                    或者只针对主要安全编码字符担心 (&, inebreaks, <, >, " and ') 比如:

                    function encode(r){
                        return r.replace(/[&
                    <>'"]/g, function(r){return "&#" + r.charCodeAt(0) + ";"})
                    }
                    
                    test.value = encode('How to encode
                    only html tags &<>'" nice & fast!');
                    
                    /*************
                    * & is &ampersand (it has to be first),
                    * 
                     is newline,
                    *************/
                    &lt;textarea id=test rows="9" cols="55"&gt;www.WHAK.com&lt;/textarea&gt;

                    【讨论】:

                      【解决方案19】:

                      我们可以使用JavaScript的DOMParser来进行特殊字符的转换。

                      const parser = new DOMParser();
                      const convertedValue = (parser.parseFromString("&#039 &amp &#039 &lt &gt", "application/xml").body.innerText;
                      

                      【讨论】:

                        【解决方案20】:

                        如果您使用的是Lodash,您可以这样做(从文档中复制粘贴):

                        _.escape('fred, barney, & pebbles');
                        // => 'fred, barney, &amp; pebbles'
                        

                        了解更多信息:_.escape([string=''])

                        【讨论】:

                          【解决方案21】:

                          我自己为此苦苦挣扎了一段时间,但我决定使用这个负匹配正则表达式来匹配所有特殊字符并将它们转换为相关的字符代码:

                          var encoded = value.replace(/[^A-Za-z0-9]/g, function(i) {
                              return '&#' + i.charCodeAt(0) + ';';
                          });
                          

                          【讨论】:

                            【解决方案22】:

                            是的,但是如果您需要将生成的字符串插入某处而不将其转换回来,则需要执行以下操作:

                            str.replace(/'/g,"&amp;amp;#39;"); // and so on
                            

                            【讨论】:

                            • “是”是对其他答案的回应?
                            • 我想是的——那是很久以前的事了。
                            【解决方案23】:
                            <html>
                                <body>
                                    <script type="text/javascript">
                                        var str = "&"'<>";
                                        alert('B4 Change: 
                            ' + str);
                            
                                        str = str.replace(/&/g, '&amp;');
                                        str = str.replace(/</g,  '&lt;');
                                        str = str.replace(/>/g,  '&gt;');
                                        str = str.replace(/"/g, '&quot;');
                                        str = str.replace(/'/g, '&#039;');
                            
                                        alert('After change: 
                            ' + str);
                                    </script>
                                </body>
                            </html>
                            

                            用这个来测试:http://www.w3schools.com/js/tryit.asp?filename=tryjs_text

                            【讨论】:

                            • 链接已损坏:“您要的文件不存在”
                            【解决方案24】:

                            以下是在 JavaScript 中对 XML 转义字符进行编码的函数:

                            Encoder.htmlEncode(unsafeText);
                            

                            【讨论】:

                              【解决方案25】:

                              使用 JavaScript 函数escape(),它可以让您对字符串进行编码。

                              例如。,

                              escape("yourString");
                              

                              【讨论】:

                              • 用于放入 URL 而非 HTML 的编码(并且该函数已被弃用,因为它已被 Unicode 破坏)。
                              猜你喜欢
                              • 2022-12-01
                              • 2015-04-15
                              • 1970-01-01
                              • 2022-12-02
                              • 2022-12-02
                              • 2018-05-26
                              • 2022-12-28
                              • 1970-01-01
                              相关资源
                              最近更新 更多