38

I am struggling with the following problem. Using javascript I would like to change the character set of a file content and display this content to the user.

I have an input:file form. On change I am reading the content

$('#form input:file').change(function(event){                   
   file = this.files[0];
   reader = new FileReader();
   reader.onload = function(event) {
      result = event.target.result.replace(/\n/g,'<br />');
      $('#filecontents').html(result);
   });
   reader.readAsText(file);
})

The file is in Windows-1251. I would like to convert the content of the file to another encoding and after that present it to the user.

Is this possible to achieve with javascript?

Regards

1 Answer 1

73

If your HTML page is in UTF-8 and your file is in ISO-8859-1.

This is working:

 reader.readAsText(file, 'ISO-8859-1');

I don't have any Windows-1251 file so I was not able to test it but it looks like that the 'CP1251' is supported (by Google Chrome at least), so:

 reader.readAsText(file, 'CP1251');

If none of this is working. Then you should change the formatting manually. Unfortunately, I am not aware of any JavaScript library that does the trick.

From the unicode mapping here and from Delan Azabani answer, you should manage to build a function that convert char by char your string in CP1251 to UTF-8.

Sign up to request clarification or add additional context in comments.

3 Comments

Regarding your last sentence, isn't there a "standard" function to convert a ISO-8859-1 string to UTF-8?
I tried this with a Shift-JIS file as follows: reader.readAsText(f, "Shift-JIS"); which converted to UTF-8 just fine. But now the problem is how to detect that the incoming file is encoded in Shift-JIS...because if I try to send a UTF-8 encoded file into that function it doesn't seem to convert properly.
This helped me a lot as I was having character encoding issues, but it turned out to be due to me using .readAsDataURL and then Base64 decoding instead of just using .readAsText and I'm done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.