public static final String escape(String s){
  StringBuffer buf=new StringBuffer();
  for (int i=0; i < s.length(); ) {
    int c=UTF16.charAt(s,i);
    i+=UTF16.getCharCount(c);
    if (c >= ' ' && c <= 0x007F) {
      if (c == '\\') {
        buf.append("\\\\");
      }
 else {
        buf.append((char)c);
      }
    }
 else {
      boolean four=c <= 0xFFFF;
      buf.append(four ? "\\u" : "\\U");
      hex(c,four ? 4 : 8,buf);
    }
  }
  return buf.toString();
}

public static final String escape ( String s ) { StringBuffer buf = new StringBuffer ( ) ; for ( int i = 0 ; i < s . length ( ) ; ) { int c = UTF16 . charAt ( s , i ) ; i += UTF16 . getCharCount ( c ) ; if ( c >= ' ' && c <= 0x007F ) { if ( c == '\\' ) { buf . append ( "\\\\" ) ; } else { buf . append ( ( char ) c ) ; } } else { boolean four = c <= 0xFFFF ; buf . append ( four ? "\\u" : "\\U" ) ; hex ( c , four ? 4 : 8 , buf ) ; } } return buf . toString ( ) ; }
convert characters outside the range u + 0020 to u + 007f to unicode escapes , and convert backslash to a double backslash .
