文本解码器
TextDecoder - Web API 接口参考 | MDN https://developer.mozilla.org/zh-CN/docs/web/api/textdecoder
TextDecoder
接口表示一个文本解码器,一个解码器只支持一种特定文本编码,例如 UTF-8
、ISO-8859-2
、KOI8-R
、GBK
,等等。解码器将字节流作为输入,并提供码位流作为输出。
备注: 此特性在 Web Worker 中可用
构造函数
TextDecoder()
-
返回一个新构造的
TextDecoder
,它使用参数中指定的解码方法生成码位流。
属性
TextDecoder
接口不继承任何属性。
TextDecoder.prototype.encoding
只读-
一个包含的解码器名称的字符串,即描述
TextDecoder
将使用的方法的字符串。 TextDecoder.prototype.fatal
只读-
一个布尔值,表示错误模式是否致命。
TextDecoder.prototype.ignoreBOM
只读-
一个布尔值,表示是否忽略字节顺序标记(BOM)标记。
方法
TextDecoder
接口不继承任何方法。
TextDecoder.prototype.decode()
-
返回一个字符串,其中包含使用特定
TextDecoder
对象的方法解码的文本。
示例
用类型化数组表示文本
本示例展示如何解码中文/日语字符,用五个不同的类型化数组表示:
Uint8Array
、Int8Array
、Uint16Array
、Int16Array
和 Int32Array
。
1 2 3 4 5 6 7 8 9 10 11 12 13 | let utf8decoder = new TextDecoder(); // default 'utf-8' or 'utf8' let u8arr = new Uint8Array([240, 160, 174, 183]); let i8arr = new Int8Array([-16, -96, -82, -73]); let u16arr = new Uint16Array([41200, 47022]); let i16arr = new Int16Array([-24336, -18514]); let i32arr = new Int32Array([-1213292304]); console.log(utf8decoder.decode(u8arr)); console.log(utf8decoder.decode(i8arr)); console.log(utf8decoder.decode(u16arr)); console.log(utf8decoder.decode(i16arr)); console.log(utf8decoder.decode(i32arr)); |
处理非 UTF8 文本
在此示例中,我们对俄语文本“Привет,мир!”进行编码,它的意思是("Hello, world.")。在我们的 TextDecoder()
构造函数中,我们指定适用于西里尔字母的 Windows-1251 字符编码。
1 2 3 4 5 | const win1251decoder = new TextDecoder( "windows-1251" ); const bytes = new Uint8Array([ 207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33, ]); console.log(win1251decoder.decode(bytes)); // Привет, мир! |
分类:
javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
2020-03-28 mysqldump 内存消耗
2020-03-28 SMTP 协议发送邮件的整体过程
2020-03-28 更新gitignore后如何使其生效
2020-03-28 Git:.gitignore和.gitkeep文件的使用 让空文件夹被跟踪
2019-03-28 怎么表示自然数 陶哲轩
2019-03-28 Shell实现判断进程是否存在并重新启动脚本
2017-03-28 数据总线和流计算在城市大脑中的应用