Java Unicode Unescape unescapeUnicode(String s)

Here you can find the source of unescapeUnicode(String s)

Description

Unescape %XX and %uXXXX notation produced by the JavaScript's escape function

License

Open Source License

Declaration

public static String unescapeUnicode(String s) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*  www . j  a va2s  .c o  m*/
     * Unescape %XX and %uXXXX notation produced by the JavaScript's escape function
     */
    public static String unescapeUnicode(String s) {
        if (s == null || s.indexOf('%') == -1)
            return s;

        StringBuilder unicode = new StringBuilder(1024);
        StringBuilder sb = new StringBuilder(4);
        boolean hadPct = false;
        boolean inUnicode = false;
        boolean inByte = false;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (inUnicode) {
                sb.append(c);

                if (sb.length() == 4) {
                    // sb now contains the four hex digits
                    // which represents our unicode character
                    try {
                        int value = Integer.parseInt(sb.toString(), 16);
                        unicode.append((char) value);
                    } catch (Exception e) {
                    } // skip bad char
                    sb.setLength(0);
                    inUnicode = false;
                    hadPct = false;
                }
                continue;
            } else if (inByte) {
                sb.append(c);

                if (sb.length() == 2) {
                    try {
                        int value = Integer.parseInt(sb.toString(), 16);
                        unicode.append((char) value);
                    } catch (Exception e) {
                    } // skip bad char
                    sb.setLength(0);
                    inByte = false;
                    hadPct = false;
                }
                continue;
            }

            if (hadPct) {
                // handle an escaped value
                hadPct = false;

                if (c == 'u')
                    inUnicode = true;
                else {
                    sb.append(c);
                    inByte = true;
                }

                continue;
            } else if (c == '%') {
                hadPct = true;
                continue;
            }

            unicode.append(c);
        }

        return unicode.toString();
    }
}

Related

  1. unescapeHTMLUnicodeEntity(final String text)
  2. unescapeUnicode(String encoded)
  3. unescapeUnicode(String s)
  4. unescapeUnicodeChars(String string)