简体   繁体   中英

Javascript: How to encode from utf-8 to iso-8859-1 and also decode from it

I have a text in UTF8, and I want to convert it to iso-8859-1. Also I have a text in iso-8859-1 and I want to encode to UTF8.

I think it is not possible using native functions, so is there any good library to do this? I am using pure javascript for browser, not nodejs, no using webpack, etc.

Thank you.

You need to use decodeURIComponent in addition to escape to go to/from UTF8/ ISO-8859-1

See this article for more info on it.

Decode UTF-: fixedstring = decodeURIComponent(escape(utfstring));

Decode ISO-8859-1: utfstring = unescape(encodeURIComponent(originalstring));

To see if a string is 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM