HTML-encoding lost when attribute read from input field

前端 未结 25 3905
时光说笑
时光说笑 2020-11-21 04:04

I’m using JavaScript to pull a value out from a hidden field and display it in a textbox. The value in the hidden field is encoded.

For example,



        
25条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 05:04

    Here's a little bit that emulates the Server.HTMLEncode function from Microsoft's ASP, written in pure JavaScript:

    function htmlEncode(s) {
      var ntable = {
        "&": "amp",
        "<": "lt",
        ">": "gt",
        "\"": "quot"
      };
      s = s.replace(/[&<>"]/g, function(ch) {
        return "&" + ntable[ch] + ";";
      })
      s = s.replace(/[^ -\x7e]/g, function(ch) {
        return "&#" + ch.charCodeAt(0).toString() + ";";
      });
      return s;
    }

    The result does not encode apostrophes, but encodes the other HTML specials and any character outside the 0x20-0x7e range.

提交回复
热议问题