Java encoding similiar to JavaScript encodeURIComponent

February 20, 2012 in JavaScript, Web 2.0

You may have a REST service that returns an encoded output to a JavaScript client which decodes this output in the client side. Unfortunately, this scenario will not always work because of the mismatch between both the Java encode() API and the JavaScript encodeURIComponent().

To be able to make the encode() behavior equivalent to the JavaScript encodeURIComponent(), all what you should do is the following String replacements.

public static String encodeURIComponent(String component)   {     
	String result = null;      
	try {       
		result = URLEncoder.encode(component, "UTF-8")   
			   .replaceAll("\\%28", "(")                          
			   .replaceAll("\\%29", ")")   		
			   .replaceAll("\\+", "%20")                          
			   .replaceAll("\\%27", "'")   			   
			   .replaceAll("\\%21", "!")
			   .replaceAll("\\%7E", "~");     
	catch (UnsupportedEncodingException e) {       
		result = component;     
	return result;   

After that you can safely decode the output in the client side using the JavaScript decodeURIComponent().


3 responses to Java encoding similiar to JavaScript encodeURIComponent

  1. This appears to be essentially the same code developed by John Topley who also provides a JAVA decodeURICompoenent. (You can see his posting and earlier attempts at

    Its good to have such a clean solution posted several places on the web, and it may be that these were independently developed, but if you did base your solution on his, it is also good to give reference to prior developers.

  2. Yes David, It was one of my references, I added it to the reference section. Thanks for reminding me.

  3. Thanks! This post helped me alot!

Skip to toolbar