简体   繁体   中英

JavaScript equivalent to URLEncoder.encode(“String”, “UTF-8”) of Java

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.

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); 

发现应该替换另外一个字符.replace(/ \\ $ / g,“%24”)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM