how to get big5 urlencode in node.js?

筅森魡賤 提交于 2019-12-06 15:43:29

because %51 is char 'Q' in big5, so '%A4Q' is equal to '%A4%51', the urlencode parse it.

what's more, the 'A' in '%A4Q' is case-insensitive, while the 'Q' is not, because 'Q' and 'q' is defferent(%51 and %71)

Based on @user1783292's answer above, I write the code bellow.

var Iconv = require('iconv').Iconv;
var iconv = new Iconv('utf8', 'BIG5');

function big5_encode(chr) {
    var rtn = "";
    var buf = iconv.convert(chr);
    for(var i=0;i<buf.length;i+=2) {
        rtn += '%' + buf[i].toString(16).toUpperCase();
        rtn += ((buf[i+1] >= 65 && buf[i+1] <= 90)
            ||(buf[i+1]>=97 && buf[i+1]<=122))
            ? String.fromCharCode(buf[i+1])
            : '%' + buf[i+1].toString(16).toUpperCase();
    }
    return rtn;
}

var chr = '十尢我';
console.log(big5_encode(chr));

the output is %A4Q%A4q%A7%DA, same as Chrome.

Maybe there is some standard rule about big5 url encode, but I do not find it. And Java's URLDecoder may also ignore such rules(so it's not correct).

I believe someone might need decode function.lol

function big5_urldecode(str){
  var tokens = str.split("%").slice(1);
  var chars = [];
  tokens.forEach((token)=>{
    chars.push(parseInt(token.substring(0,2),16));
    if(token.length > 2){
      chars.push(token.charCodeAt(2));
    }
  });
  return chars;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!