JS text-encoding 进行GBK编码解码

npm install text-encoding --save

import {
  TextEncoder,
  TextDecoder
} from 'text-encoding'

/**
 * 编码
 * @param {*} str 需要编码的字符串
 * @param {*} encoding 编码类型(gb2312,utf-8)
 * @returns unit8Array类型的对象
 */
export function encode(str, encoding) {
  let encode = new TextEncoder(encoding, {
    NONSTANDARD_allowLegacyEncoding: true
  })
  let uint8Array = encode.encode(str);
  return uint8Array;
}


/**
 * 解码
 * @param {*} uint8Array 需要解码的unit8Array类型的对象
 * @param {*} encoding 解码类型(gb2312,utf-8)
 * @returns 解码出来的字符串
 */
export function decode(uint8Array, encoding) {
  let decode = new TextDecoder(encoding);
  return decode.decode(uint8Array)
}

注1:编码出来的是unit8Array对象,解码的时候需要new Uint8Array(arr)一个字节数组生成
注2:encoding是解码类型,gbk填gb2312

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容