浏览器/node环境下 big5/gbk编码的字符串 urlencode

本文介绍了如何在浏览器和Node.js环境中对采用big5或gbk编码的字符串进行urlencode操作。首先,讲解了浏览器端的实现方法,接着阐述了在Node.js环境下转换和编码的步骤,重点关注UTF8到GBK的转换过程。
摘要由CSDN通过智能技术生成

浏览器端

function urlencode(str, charset, callback) {
  //创建form通过accept-charset做encode
  var form = document.createElement("form");
  form.method = "get";
  form.style.display = "none";
  form.acceptCharset = charset;
  if (document.all) {
    //如果是IE那么就调用document.charset方法
    window.oldCharset = document.charset;
    document.charset = charset;
  }
  var input = document.createElement("input");
  input.type = "hidden";
  input.name = "str";
  input.value = str;
  form.appendChild(input);
  form.target = "_urlEncode_iframe_";
  document.body.appendChild(form);
  //隐藏iframe截获提交的字符串
  if (!window["_urlEncode_iframe_"]) {
    var iframe;
    if (document.all) {
      try {
        iframe = document.createElement(
          '<iframe name="_urlEncode_iframe_"></iframe>'
        );
      } catch (e) {
        iframe = document.createElement("iframe");
        //iframe.name = '_urlEncode_iframe_';
        iframe.setAttribute("name", "_urlEncode_iframe_");
      }
    } else {
      iframe = document.createElement("iframe");
      //iframe.name = '_urlEncode_iframe_';
      iframe.setAttribute("name", "_urlEncode_iframe_");
    }
    iframe.style.display = "none";
    iframe.width = "0";
    iframe.height = "0";
    iframe.scrolling = "no";
    iframe.allowtransparency = "true";
    iframe.frameborder = "0";
    iframe.src = "about:blank";
    document.body.appendChild(iframe);
  }
  //
  window._urlEncode_iframe_callback = function (str) {
    callback(str);
    if (document.all) {
      document.charset = window.oldCharset;
    }
  };
  //设置回调编码页面的地址,这里需要用户修改
  form.action = "/res/urlencode_files/getEncodeStr.html";
  form.submit();
  setTimeout(function () {
    form.parentNode.removeChild(form);
    iframe.parentNode.removeChild(iframe);
  }, 500);
}


function urldecode(str, charset, callback) {
  var script = document.createElement("script");
  script.id = "_urlDecodeFn_";
  window._urlDecodeFn_ = callback;
  if (document.all) {
    if (navigator.userAgent.indexOf("MSIE 8") > -1) {
      //对于ie8做特别hack
      var link = document.createElement("link");
      link.rel = "stylesheet";
      link.type = "text/css";
      link.charset = charset;
      link.href =
        "data:text/plain;charset=" +
        charset +
        ",%23_decode_hidden_el_for_test_%7Bbackground-image%3Aurl(" +
        str +
        ")%7D";
      alert(link.href);
      document.body.appendChild(link);
      //然后创建一个隐藏的div,应用这个样式
      var div = document.createElement("div");
      div.id = "_decode_hidden_el_for_test_";
      div.style.display = "none";
      document.body.appendChild(div);
      setTimeout(function () {
        callback(
          document
            .getElementById("_decode_hidden_el_for_test_")
            .currentStyle["backgroundImage"].match(/\("data\:text\/(.+)"\)/)[1]
        );
        link.parentNode.removeChild(link);
        div.parentNode.removeChild(div);
      }, 300);
    } else {
      //隐藏iframe截获提交的字符串
      if (!window["_urlDecode_iframe_"]) {
        var iframe;
        if (document.all) {
          try {
            iframe = document.createElement(
              '<iframe name="_urlDecode_iframe_"></iframe>'
            );
          } catch (e) {
            iframe = document.createElement("iframe");
            //iframe.name = '_urlDecode_iframe_';
            iframe.setAttribute("name", "_urlDecode_iframe_");
          }
        } else {
          iframe = document.createElement("iframe");
          //iframe.name = '_urlDecode_iframe_';
          iframe.setAttribute("name", "_urlDecode_iframe_");
        }
        //iframe.name = '_urlDecode_iframe_';
        iframe.setAttribute("name", "_urlDecode_iframe_");
        iframe.style.display = "none";
        iframe.width = "0";
        iframe.height = "0";
        iframe.scrolling = "no";
        iframe.allowtransparency = "true";
        iframe.frameborder = "0";
        iframe.src = "about:blank";
        document.body.appendChild(iframe);
      }
      //ie下需要指明charset,然后src=datauri才可以
      iframe.contentWindow.document.write(
        "<html><scrip" +
          't charset="gbk" src="data:text/javascript;charset=gbk,parent._decodeStr_=\'' +
          str +
          "'\"></s" +
          "cript></html>"
      );
      setTimeout(function () {
        callback(_decodeStr_);
        iframe.parentNode.removeChild(iframe);
      }, 300);
    }
  } else {
    var src =
      "data:text/javascript;charset=" +
      charset +
      ',_urlDecodeFn_("' +
      str +
      '");';
    src +=
      'document.getElementById("_urlDecodeFn_").parentNode.removeChild(document.getElementById("_urlDecodeFn_"));';
    script.src = src;
    document.body.appendChild(script);
  }
}

urlencode("编码和解码", "big5", (str) => console.log(str)); // "%26%2332534%3B%26%2330721%3B%A9M%B8%D1%26%2330721%3B"

urlencode("%26%2332534%3B%26%2330721%3B%A9M%B8%D1%26%2330721%3B", "big5", (str) => console.log(str)); // "编码和解码"

node端

npm install urlencode

var urlencode = require('urlencode');

console.log(urlencode('苏千')); // default is utf8
console.log(urlencode('苏千', 'gbk')); // '%CB%D5%C7%A7'

// decode gbk
urlencode.decode('%CB%D5%C7%A7', 'gbk'); // '苏千'

// parse gbk querystring
urlencode.parse('nick=%CB%D5%C7%A7', {charset: 'gbk'}); // {nick: '苏千'}

// stringify obj with gbk encoding
var str = 'x[y][0][v][w]=' + urlencode('雾空', 'gbk'); // x[y][0][v][w]=%CE%ED%BF%D5
var obj =  {'x' : {'y' : [{'v' : {'w' : '雾空'}}]}};
urlencode.stringify(obj, {charset: 'gbk'}).should.equal(str);

UTF8ToGBK

const iconv = require('iconv-lite');

let UTF8ToGBK = (str, encoding) => {
    let from = iconv.encode(str, encoding);
    var rt = '';
    for (var i = 0; i < from.length; i++) {
        var c = from.readUInt8(i);
        if (c > 127) {
            i++;
            var c2 = from.readUInt8(i);
            rt += '%' + c.toString(16).toUpperCase() + '%' + c2.toString(16).toUpperCase();
        } else {
            rt += String.fromCharCode(c);
        }
    }
    return rt;
}

UTF8ToGBK("编码和解码","gbk")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值