EN
Java - encodeURIComponent equivalent in JavaScript
10
points
Using Java sometimes it is necessar to encode some data to send inside url. In JavaScript is avaialble encodeURIComponent
function. What has been shown below:
// ONLINE-RUNNER:browser;
var text = 'Hi! How are you? Dangerous characters: ?#&';
var encodedText = encodeURIComponent(text);
console.log(encodedText);
Note: check
decodeURIComponent
here.
1. Java encodeURIComponent
equivalent example
URIEncoder.java
file:
package com.dirask.examples;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class URIEncoder {
private static final String[][] CHARACTERS = {
{ "\\+", "%20" },
{ "\\%21", "!" },
{ "\\%27", "'" },
{ "\\%28", "(" },
{ "\\%29", ")" },
{ "\\%7E", "~" }
};
public static String encodeURIComponent(String text)
throws UnsupportedEncodingException {
String result = URLEncoder.encode(text, "UTF-8"); // StandardCharsets.UTF_8
for(String[] entry : CHARACTERS) {
result = result.replaceAll(entry[0], entry[1]);
}
return result;
}
}
Program.java
file:
package com.dirask.examples;
import java.io.UnsupportedEncodingException;
public class Program {
public static void main(String[] args)
throws UnsupportedEncodingException {
String text = "Hi! How are you? Dangerous characters: ?#&";
String encodedText = URIEncoder.encodeURIComponent(text);
System.out.println(encodedText);
}
}
Output:
Hi!%20How%20are%20you%3F%20Dangerous%20characters%3A%20%3F%23%26