简体   繁体   中英

JavaScript Encode from “UTF-8” to “cp1252”

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".

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.

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