0

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.

Black Cid
  • 438
  • 1
  • 7
  • 21
  • This could be asked at https://softwarerecs.stackexchange.com/, but make sure you've read their [help section](https://softwarerecs.stackexchange.com/help/asking) before asking. – Teemu Apr 24 '20 at 08:55
  • What kind of browser support do you need? – Ry- May 11 '20 at 21:23

1 Answers1

-1

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;
}
Joel Hager
  • 2,990
  • 3
  • 15
  • 44
  • 1
    This only works for strings that are exactly equal in UTF8 than ISO-8859-1. That's can't be called decoding. Just tested with one simple accent like "á" and throwed "malformed URI". This is 100% useless. – Black Cid May 11 '20 at 13:26
  • 1
    @BlackCid: You sure? `unescape(encodeURIComponent('á')) === String.fromCharCode(...new TextEncoder().encode('á'))` – Ry- May 11 '20 at 21:26