如何将URL中的UTF-8字符串转成对应的中文字符串

在项目中我们有时需要将url中的UTF-8字符串转换成中文使用。

getCharFromUtf8(str) {
  var cstr = "";
  var nOffset = 0;
  if (str == "")
    return "";
  str = str.toLowerCase();
  nOffset = str.indexOf("%e");
  if (nOffset == -1)
    return str;
  while (nOffset != -1) {
    cstr += str.substr(0, nOffset);
    str = str.substr(nOffset, str.length - nOffset);
    if (str == "" || str.length < 9)
      return cstr;
    cstr += this.utf8ToChar(str.substr(0, 9));
    str = str.substr(9, str.length - 9);
    nOffset = str.indexOf("%e");
    }
    return cstr + str;
  },
  utf8ToChar(str) { 
    var iCode, iCode1, iCode2; 
    iCode = parseInt("0x" + str.substr(1, 2)); 
    iCode1 = parseInt("0x" + str.substr(4, 2)); 
    iCode2 = parseInt("0x" + str.substr(7, 2)); 
    return String.fromCharCode(((iCode & 0x0F) << 12) | ((iCode1 & 0x3F) << 6) | (iCode2 & 0x3F)); 
} ,
posted @ 2021-08-01 21:03  zhongfang99  阅读(467)  评论(0编辑  收藏  举报