2

I want to encode a string to UTF-8 in JavaScript. In java we use URLEncoder.encode("String", "UTF-8") to achieve this.

I know we can use encodeURI or encodeURIComponent but it is producing different output than URLEncoder.encode

Can anyone please suggest any available JS method that can be used to achieve same output as URLEncoder.encode.

NOTE: Due to restrictions I cannot use jQuery.

Sandeep Kumar
  • 13,799
  • 21
  • 74
  • 110

2 Answers2

0

I don't know if this javaURLEncode() function is a spot-on match for Java's URLEncoder.encode method, but it might be close to what you're looking for:

function javaURLEncode(str) {
  return encodeURI(str)
    .replace(/%20/g, "+")
    .replace(/!/g, "%21")
    .replace(/'/g, "%27")
    .replace(/\(/g, "%28")
    .replace(/\)/g, "%29")
    .replace(/~/g, "%7E");
}

var testString = "It's ~ (crazy)!";
var jsEscape = escape(testString);
var jsEncodeURI = encodeURI(testString);
var jsEncodeURIComponent = encodeURIComponent(testString);
var javaURLEncoder = javaURLEncode(testString);
alert("Original: " + testString + "\n" +
  "JS escape: " + jsEscape + "\n" +
  "JS encodeURI: " + jsEncodeURI + "\n" +
  "JS encodeURIComponent: " + jsEncodeURIComponent + "\n" +
  "Java URLEncoder.encode: " + javaURLEncoder);
Troy Gizzi
  • 2,480
  • 1
  • 14
  • 15
0

found one more character should be replaced .replace(/\$/g, "%24")

Quimby
  • 331
  • 2
  • 4