1

I'd like to encode a string from "UTF-8" to "cp1252" with JavaScript.

I have an HTML document sent as utf-8, and in that document there is a hidden field keep the JsonString which contain "UTF-8" characters such as "二". My Java Bean doesn't receive the correct value on the server-side, it gets "?".

    <h:inputHidden id="hiddenPropertiesValues" 
        value="#{Bean.newProperties}"/>

Java Bean class sscce

    public void setNewProperties( String newProperties ) {
        this.newProperties = newProperties;
    }

I tried to trans-code the JsonString to "cp1252" by java code first. And then input the trans-coded JsonString to the hidden field. The Bean can get the correct characters.

So I thought I can solve this problem by encoding the string from "UTF-8" to "cp1252" with JavaScript.

Both of the Html and the Java Bean files use "UTF-8".

cindy
  • 213
  • 3
  • 10
  • Related: http://stackoverflow.com/questions/2283829/how-do-i-transcode-a-javascript-string-to-iso-8859-1 –  Dec 25 '12 at 08:57
  • What exactly do you want to do with the result? – user123444555621 Dec 25 '12 at 09:18
  • @Pumbaa80 If there is a String str = "二"; which is encode "UTF-8".I want to transcode it to "ISO8859_1". Then it will show as some strange string. – cindy Dec 25 '12 at 09:27
  • It is really hard to answer your question if we have to guess what's happening. So I *think* you have an HTML document sent as utf-8, and in that document you are creating a form with JS, which should be sent as iso8859-1. In that form, there should be a hidden field that is given some value by JS. But when you assign `"二"`, your Java Bean does not recieve the correct value on the server-side. Is that it? If so, please update your question. – user123444555621 Dec 25 '12 at 09:39
  • 1
    ISO-8859 cannot encode the character "二". – deceze Dec 25 '12 at 12:32

1 Answers1

2

First, it is not possible to do so, because Unicode contains way more characters than ISO8859-1.

Second, you should (almost) never need to worry about encodings, since the browser handles that for you. Internally, JS always uses UTF-16, no matter what the document encoding is. When you use document.write or DOM manipulation, and when a form requires a certain encoding, the browser will take care of converting.

I think what you really should do is improve your server-side implementation and switch to UTF-8 there.

user123444555621
  • 148,182
  • 27
  • 114
  • 126