首页 > 解决方案 > Javascript:如何从 utf-8 编码到 iso-8859-1 并从中解码

问题描述

我有一个 UTF8 文本,我想将其转换为 iso-8859-1。此外,我在 iso-8859-1 中有一个文本,我想编码为 UTF8。

我认为使用本机函数是不可能的,那么有什么好的库可以做到这一点吗?我在浏览器中使用纯 javascript,而不是 nodejs,不使用 webpack 等。

谢谢你。

标签: javascriptencodingutf-8iso-8859-1

解决方案


你需要使用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;
}

推荐阅读