Languages
[Edit]
EN

Java - decodeURIComponent equivalent in JavaScript

3 points
Created by:
Kate_C
19790

Using Java sometimes it is necessar to decode some data inside url. In JavaScript is avaialble decodeURIComponent function. What has been shown below:

// ONLINE-RUNNER:browser;

var text = 'Hi!%20How%20are%20you%3F%20Dangerous%20characters%3A%20%3F%23%26';
var decodedText = decodeURIComponent(text);

console.log(decodedText);

Note: check encodeURIComponent here.

1. Java decodeURIComponent equivalent example

URIDecoder.java file:

package com.dirask.examples;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class URIDecoder {

    private static final String[][] CHARACTERS = {
        { "\\%20",   "+" },
        {     "!", "%21" },
        {     "'", "%27" },
        {   "\\(", "%28" },
        {   "\\)", "%29" },
        {     "~", "%7E" }
    };

    public static String decodeURIComponent(String text) 
        throws UnsupportedEncodingException {

        for(String[] entry : CHARACTERS) {
            text= text.replaceAll(entry[0], entry[1]);
        }

        return URLDecoder.decode(text, "UTF-8"); // StandardCharsets.UTF_8
    }
}

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!%20How%20are%20you%3F%20Dangerous%20characters%3A%20%3F%23%26";
        String decodedText = URIDecoder.decodeURIComponent(text);

        System.out.println(decodedText);
    }
}

Output:

Hi! How are you? Dangerous characters: ?#&

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join