Languages
[Edit]
EN

Java - decodeURIComponent equivalent in JavaScript

3 points
Created by:
Kate_C
2845

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: ?#&

 

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍