Escape characters that should not be included in a variable in a URL. - Java java.lang

Java examples for java.lang:String Escape

Description

Escape characters that should not be included in a variable in a URL.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String input = "java2s.com";
        System.out.println(urlEscape(input));
    }//from w w w.ja v a2s.  co  m

    /**
     * Escape characters that should not be included in a variable in a URL. It
     * is different to using URLEncoder.encode() because it escapes only what
     * is really needed to be escaped for modern browsers.
     *
     * Technically it is incorrect, but it makes for much nicer looking URL's
     * when working with non English languages.
     *
     * @param input
     *
     * @return The input string, with a limited set of special characters escaped.
     */
    public static String urlEscape(String input) {
        input = input.replace("%", "%25");
        input = input.replace("+", "%2B");
        input = input.replace("=", "%3D");
        input = input.replace("#", "%23");
        input = input.replace("/", "%2F");
        input = input.replace("@", "%40");
        input = input.replace("&", "%26");
        input = input.replace("\n", "%0A");
        input = input.replace("\r", "%0C");
        input = input.replace("\"", "%22");
        input = input.replace("<", "%3C");
        input = input.replace(">", "%3E");
        input = input.replace("'", "%27");
        input = input.replace(" ", "%20");
        return input;
    }
}

Related Tutorials