Java Javascript String Unescape unescapeJavaScriptString(String string)

Here you can find the source of unescapeJavaScriptString(String string)

Description

Unescape JS strings and return them, surrounded by single quotes.

License

Apache License

Parameter

Parameter Description
string The string to unescape

Return

The unescaped string

Declaration

public static String unescapeJavaScriptString(String string) 

Method Source Code

//package com.java2s;
/*/*w w  w. j  a  v  a2s  .  com*/
 * Copyright 2011 Chad Retz
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

public class Main {
    /**
     * Unescape JS strings and return them, surrounded by single quotes.
     * Specifically, this unescapes \b, \f, \n, \0, \r, \t, and single quotes.
     * 
     * @param string The string to unescape
     * @return The unescaped string
     */
    public static String unescapeJavaScriptString(String string) {
        StringBuilder ret = new StringBuilder(string.length()).append('\'');
        for (int i = 0; i < string.length(); i++) {
            char chr = string.charAt(i);
            switch (chr) {
            case '\b':
                ret.append("\\b");
                break;
            case '\f':
                ret.append("\\f");
                break;
            case '\n':
                ret.append("\\n");
                break;
            case '\0':
                //TODO: does this even work?
                ret.append("\\0");
                break;
            case '\r':
                ret.append("\\r");
                break;
            case '\t':
                ret.append("\\t");
                break;
            case '\'':
                ret.append("\\'");
                break;
            default:
                ret.append(chr);
            }
        }
        return ret.append('\'').toString();
    }
}

Related

  1. unescapeJavaScript(String value)
  2. unescapeJavascriptParam(String s)
  3. unescapeJavaString(String st)
  4. unescapeJavaString(String str)