Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

Java - encodeURIComponent equivalent in JavaScript

0 contributions
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

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more