javascript - Javascript:如何从 utf-8 编码到 iso-8859-1 并从中解码
问题描述
我有一个 UTF8 文本,我想将其转换为 iso-8859-1。此外,我在 iso-8859-1 中有一个文本,我想编码为 UTF8。
我认为使用本机函数是不可能的,那么有什么好的库可以做到这一点吗?我在浏览器中使用纯 javascript,而不是 nodejs,不使用 webpack 等。
谢谢你。
解决方案
你需要使用decodeURIComponent
除了escape
去/来自 UTF8/ISO-8859-1
有关它的更多信息,请参阅这篇文章。
解码 UTF-:fixedstring = decodeURIComponent(escape(utfstring));
解码 ISO-8859-1:utfstring = unescape(encodeURIComponent(originalstring));
要查看字符串是否为 UTF-8:
var fixedstring;
try{
// If the string is UTF-8, this will work and not throw an error.
fixedstring=decodeURIComponent(escape(badstring));
}catch(e){
// If it isn't, an error will be thrown, and we can assume that we have an ISO string.
fixedstring=badstring;
}
推荐阅读
- scala - 找不到 GeneratorDrivenPropertyChecks 特征
- python - 创建表列时如何正确使用 ON UPDATE CURRENT_TIMESTAMP?
- delphi - IDE 插件禁用插入键
- rust-tokio - 有没有办法在 tokio 0.2 中将 tokio::main 与单线程运行时一起使用?
- .net - Mvc 路由 - 多匹配 URL
- c++ - CRTP如何使派生类具有基类的容器
- javascript - 从 ajax(香草版)发送的数据不会存储在 PHP 中的 $_POST 中
- java - 有没有更干净的方法来写这个?
- php - 如何检查字符串中是否只有制表符(\ t char)
- date - 使用 Dask map_partitions 将日期和时间从两列转换为单个日期时间列