Home » Javascript » Convert a variable containing UTF8 string to a variable containing latin1 string – for browser in Javascript

Convert a variable containing UTF8 string to a variable containing latin1 string – for browser in Javascript

Posted by: admin November 1, 2017 Leave a comment

Questions:

Bash alternative (shell set to UTF8):

Input:

in.json

$ file -I in.json
in.json: text/plain; charset=utf-8

{“it-it”:”Città”}

Bash command I need the JS alternative for:

$ iconv -f utf8 -t latin1 in.json > out.json

out.json

$ file -I in.json
out.json: text/plain; charset=iso-8859-1

{“it-it”:”Citt?”}

What Javascript sees in browser for in.json when read as base64 from an input type=”file” (despite content-type and script encoding set to utf8):

{"it-it":"Città"}

What Javascript sees in browser for out.json:

{"it-it":"Città"}

Question – how can I make in the most native Javascript way to make most modern browsers convert this utf8 string

({"it-it":"Città "} as latin1 and {"it-it":"Città"} as utf8) 

to a latin1 string?

I prefer a native solution, or worst case JQuery, please try not to solve it with an npm + node dependency hell.

P.s.: I only need to support the most modern browsers, this is for an admin-only page.

Answers:

Below I’ve created an array with iso-8859-1version of CittÃ, and then used TextDecoder to decode it,.

So if you can get the binary version of the JSON, this should be able to convert for you.

//CittÃ
var latinSource = new Uint8Array([67, 105, 116, 116, 195]);

var tc = new TextDecoder("iso-8859-1");

console.log(tc.decode(latinSource));