Java String Encode encodeValue(String value)

Here you can find the source of encodeValue(String value)

Description

encode Value

License

Open Source License

Return

value encoded so that it can be passed to the client and parsed via JavaScript's decodeURIComponent().

Declaration

public static String encodeValue(String value) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright ? 2008, 2013 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from  ww w  .  j av a 2s . c  o  m
 * IBM Corporation - initial API and implementation
 *
 *******************************************************************************/

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;

public class Main {
    /**
     * @return <code>value</code> encoded so that it can be passed to the client and parsed via JavaScript's decodeURIComponent().
     */
    public static String encodeValue(String value) {
        try {
            // URLEncoder doesn't escape exactly how decodeURIComponent works.
            return URLEncoder
                    .encode(value, "UTF-8").replaceAll("\\+", "%20").replaceAll("\\%21", "!").replaceAll("\\%27", "'") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
                    .replaceAll("\\%28", "(").replaceAll("\\%29", ")").replaceAll("\\%7E", "~"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
        } catch (UnsupportedEncodingException e) {
            // Shouldn't happen, but just in case...
            return value
                    .replaceAll(" ", "%20").replaceAll("\\%21", "!").replaceAll("\\%27", "'").replaceAll("\\%28", "(") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
                    .replaceAll("\\%29", ")").replaceAll("\\%7E", "~"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
        }
    }
}

Related

  1. encodeUTF8(String input, boolean keepSpaces)
  2. encodeUTF8(String s)
  3. encodeUTF8(String s)
  4. encodeValue(String dirtyValue)
  5. encodeValue(String str)