解码UTF-8使用Javascript(Decode UTF-8 with Javascript)

2019-06-21 03:29发布

我的Javascript在被传递UTF-8编码字符串的XHTML的网页。 它需要不断地通过UTF-8版,以及解码。 怎么可能一个UTF-8字符串显示解码?

<script type="text/javascript">
// <![CDATA[
function updateUser(usernameSent){
    var usernameReceived = usernameSent; // Current value: Größe
    var usernameDecoded = usernameReceived;  // Decode to: Größe
    var html2id = '';
    html2id += 'Encoded: ' + usernameReceived + '<br />Decoded: ' + usernameDecoded;
    document.getElementById('userId').innerHTML = html2id;
}
// ]]>
</script>

Answer 1:

要回答原来的问题:这里是你如何在JavaScript解码UTF-8:

http://ecmanaut.blogspot.ca/2006/07/encoding-decoding-utf8-in-javascript.html

特别,

function encode_utf8(s) {
  return unescape(encodeURIComponent(s));
}

function decode_utf8(s) {
  return decodeURIComponent(escape(s));
}

我只是用这个在我的代码,它完美的作品。



Answer 2:

这应该工作:

// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt

/* utf.js - UTF-8 <=> UTF-16 convertion
 *
 * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
 * Version: 1.0
 * LastModified: Dec 25 1999
 * This library is free.  You can redistribute it and/or modify it.
 */

function Utf8ArrayToStr(array) {
    var out, i, len, c;
    var char2, char3;

    out = "";
    len = array.length;
    i = 0;
    while(i < len) {
    c = array[i++];
    switch(c >> 4)
    { 
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
                       ((char2 & 0x3F) << 6) |
                       ((char3 & 0x3F) << 0));
        break;
    }
    }

    return out;
}

退房的jsfiddle演示 。

另请参阅相关的问题: 在这里和这里



Answer 3:

@艾伯特的解决方案是,我认为最接近的,但它只能解析长达3字节UTF-8字符

function utf8ArrayToStr(array) {
  var out, i, len, c;
  var char2, char3;

  out = "";
  len = array.length;
  i = 0;

  // XXX: Invalid bytes are ignored
  while(i < len) {
    c = array[i++];
    if (c >> 7 == 0) {
      // 0xxx xxxx
      out += String.fromCharCode(c);
      continue;
    }

    // Invalid starting byte
    if (c >> 6 == 0x02) {
      continue;
    }

    // #### MULTIBYTE ####
    // How many bytes left for thus character?
    var extraLength = null;
    if (c >> 5 == 0x06) {
      extraLength = 1;
    } else if (c >> 4 == 0x0e) {
      extraLength = 2;
    } else if (c >> 3 == 0x1e) {
      extraLength = 3;
    } else if (c >> 2 == 0x3e) {
      extraLength = 4;
    } else if (c >> 1 == 0x7e) {
      extraLength = 5;
    } else {
      continue;
    }

    // Do we have enough bytes in our data?
    if (i+extraLength > len) {
      var leftovers = array.slice(i-1);

      // If there is an invalid byte in the leftovers we might want to
      // continue from there.
      for (; i < len; i++) if (array[i] >> 6 != 0x02) break;
      if (i != len) continue;

      // All leftover bytes are valid.
      return {result: out, leftovers: leftovers};
    }
    // Remove the UTF-8 prefix from the char (res)
    var mask = (1 << (8 - extraLength - 1)) - 1,
        res = c & mask, nextChar, count;

    for (count = 0; count < extraLength; count++) {
      nextChar = array[i++];

      // Is the char valid multibyte part?
      if (nextChar >> 6 != 0x02) {break;};
      res = (res << 6) | (nextChar & 0x3f);
    }

    if (count != extraLength) {
      i--;
      continue;
    }

    if (res <= 0xffff) {
      out += String.fromCharCode(res);
      continue;
    }

    res -= 0x10000;
    var high = ((res >> 10) & 0x3ff) + 0xd800,
        low = (res & 0x3ff) + 0xdc00;
    out += String.fromCharCode(high, low);
  }

  return {result: out, leftovers: []};
}

这将返回{result: "parsed string", leftovers: [list of invalid bytes at the end]}如果你正在分析在大块的字符串。

编辑:固定的@unhammer发现的问题。



Answer 4:

更新@艾伯特的答案的表情符号附加条件。

function Utf8ArrayToStr(array) {
    var out, i, len, c;
    var char2, char3, char4;

    out = "";
    len = array.length;
    i = 0;
    while(i < len) {
    c = array[i++];
    switch(c >> 4)
    { 
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
                       ((char2 & 0x3F) << 6) |
                       ((char3 & 0x3F) << 0));
        break;
     case 15:
        // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        char4 = array[i++];
        out += String.fromCodePoint(((c & 0x07) << 18) | ((char2 & 0x3F) << 12) | ((char3 & 0x3F) << 6) | (char4 & 0x3F));

        break;
    }

    return out;
}


Answer 5:

这里是一个溶液处理所有的Unicode码点包括上(4个字节)的值和通过所有现代浏览器(IE之外> 5.5)的支持。 它使用decodeURIComponent(),而不是过时的逃生/ UNESCAPE功能:

function utf8_to_str(a) {
    for(var i=0, s=''; i<a.length; i++) {
        var h = a[i].toString(16)
        if(h.length < 2) h = '0' + h
        s += '%' + h
    }
    return decodeURIComponent(s)
}

经过测试,可在GitHub上

从字符串创建UTF-8:

function utf8_from_str(s) {
    for(var i=0, enc = encodeURIComponent(s), a = []; i < enc.length;) {
        if(enc[i] === '%') {
            a.push(parseInt(enc.substr(i+1, 2), 16))
            i += 3
        } else {
            a.push(enc.charCodeAt(i++))
        }
    }
    return a
}

经过测试,可在GitHub上



Answer 6:

//字符串为UTF8的ByteBuffer

function strToUTF8(str){
  return Uint8Array.from(encodeURIComponent(str).replace(/%(..)/g,(m,v)=>{return String.fromCodePoint(parseInt(v,16))}), c=>c.codePointAt(0))
}

// UTF8 ByteArray的字符串

function UTF8toStr(ba){
  return decodeURIComponent(ba.reduce((p,c)=>{return p+'%'+c.toString(16),''}))
}


Answer 7:

也许使用textDecoder就足够了。

在所有的浏览器不支持,但。 但是如果你使用人行横道或者你知道是干什么用的浏览器的任何其他使用情况下,它可能就足够了。

var decoder = new TextDecoder('utf-8'),
    decodedMessage;

decodedMessage = decoder.decode(message.data);


Answer 8:

我想最简单的方法是使用内置的JS函数decodeURI()/是encodeURI()。

function (usernameSent) {
  var usernameEncoded = usernameSent; // Current value: utf8
  var usernameDecoded = decodeURI(usernameReceived);  // Decoded
  // do stuff
}


Answer 9:

用我的1.6kb的图书馆 ,你可以做

ToString(FromUTF8(Array.from(usernameReceived)))


Answer 10:

这是我一个更具体的谷歌搜索不仅仅是UTF-8编码/解码后找到。 所以对于那些谁正在寻找一个转化库编码之间进行转换,在这里你去。

https://github.com/inexorabletash/text-encoding

var uint8array = new TextEncoder().encode(str);
var str = new TextDecoder(encoding).decode(uint8array);

从回购自述贴

所有从编码规格编码的支持:

UTF-8 ibm866异8859-2异8859-3异8859-4 ISO-8859-5异8859-6异8859-7异8859-8异8859-8-i的异8859- 10 ISO-8859-13异8859-14 ISO-8859-15异8859-16 KOI8-R Koi8-U MACINTOSH窗口-874窗口-1250窗口-1251窗口1252窗口-1253窗口-1254窗口-1255窗-1256窗口-1257窗口-1258 X-MAC-西里尔GB18030 HZ-GB-2312中文EUC-JP ISO-2022-JP shift_jis访问EUC-KR替换UTF-16BE UTF-16LE的x用户定义

(一些编码可以根据其他的名称,例如ASCII,ISO-8859-1等。参见针对每个编码额外的标签编码来支持。)



Answer 11:

我搜索了一个简单的解决方案,这很适合我:

//input data
view = new Uint8Array(data);

//output string
serialString = ua2text(view);

//convert UTF8 to string
function ua2text(ua) {
    s = "";
    for (var i = 0; i < ua.length; i++) {
        s += String.fromCharCode(ua[i]);
    }
    return s;               
}

唯一的问题我已经是有时我得到一个字符的时间。 这可能是由设计,我的arraybuffer来源。 我使用https://github.com/xseignard/cordovarduino在Android设备上阅读的串行数据。



文章来源: Decode UTF-8 with Javascript