How to create an equivalent to JavaScript encodeURIComponent in Java

1 Answer

0 votes
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class Program {
    public static String encodeURIComponent(String str) {
        String result = null;
    
        try {
            result = URLEncoder.encode(str, "UTF-8")
                             .replaceAll("\\+", "%20")
                             .replaceAll("\\%21", "!")
                             .replaceAll("\\%27", "'")
                             .replaceAll("\\%28", "(")
                             .replaceAll("\\%29", ")")
                             .replaceAll("\\%7E", "~");
        }
    
        // This exception should never occur.
        catch (UnsupportedEncodingException e) {
          result = str;
        }
    
        return result;
    }  
    public static void main(String[] args) {
        String str = "https://www.seek4info.com/search.php?query=seo";
        
        System.out.print(encodeURIComponent(str));
    }
}



/*
run:

https%3A%2F%2Fwww.seek4info.com%2Fsearch.php%3Fquery%3Dseo

*/

 



answered Apr 13, 2025 by avibootz
...