Languages
[Edit]
EN

Java - encodeURIComponent equivalent in JavaScript

10 points
Created by:
Root-ssh
6253

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

 

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 👍