简体   繁体   中英

java how to escape accented character in string

For example

 {"orderNumber":"S301020000","customerFirstName":"ke ČECHA ","customerLastName":"张科","orderStatus":"PENDING_FULFILLMENT_REQUEST","orderSubmittedDate":"May 13, 2015 1:41:28 PM"}

how to get the accented character like "Č" in above json string and escape it in java

Just give some context of this question, please check this question from me Ajax unescape response text from java servlet not working properly

Sorry for my English :)

You should escape all characters that are greater than 0x7F . You can loop through the String's characters using the .charAt(index) method. For each character ch that needs escaping, replace it with:

String hexDigits = Integer.toHexString(ch).toUpperCase();
String escapedCh = "\\u" + "0000".substring(hexDigits.length) + hexDigits;

I don't think you will need to unescape them in JavaScript because JavaScript supports escaped characters in string literals, so you should be able to work with the string the way it is returned by the server. I'm guessing you will be using JSON.parse() to convert the returned JSON string into a JavaScript object, like this .


Here's a complete function:

public static escapeJavaScript(String source)
{
    StringBuilder result = new StringBuilder();

    for (int i = 0; i < source.length(); i++)
    {
        char ch = source.charAt(i);

        if (ch > 0x7F)
        {
            String hexDigits = Integer.toHexString(ch).toUpperCase();
            String escapedCh = "\\u" + "0000".substring(hexDigits.length) + hexDigits;
            result.append(escapedCh);
        }
        else
        {
            result.append(ch);
        }
    }

    return result.toString();
}

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