JavaScript encodeURI(), decodeURI(), encodeURIComponent(), decodeURIComponent()

URI:  Uniform Resource Identifier

encodeURI() And decodeURI()

  • The encodeURI() function is used to encode a URI.
  • The encodeURI() function encodes special characters, except: , / ? : @ & = + $ # (Use encodeURIComponent() to encode these characters).
  • The decodeURI() function is used to decode a URI.

Example

 1 <script>
 2     var uri = "my test.asp?name=ståle&car=saab";
 3     var enc = encodeURI(uri);
 4     var dec = decodeURI(enc);
 5     var res = "Encoded URI: " + enc + "<br>" + "Decoded URI: " + dec;
 6     document.write(res);
 7 </script>
 8 // Result
 9 Encoded URI: my%20test.asp?name=st%C3%A5le&car=saab
10 Decoded URI: my test.asp?name=ståle&car=saab 

encodeURIComponent() And decodeURIComponent()

  • The encodeURIComponent() function encodes a URI component.
  • This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #.
  • The decodeURIComponent() function decodes a URI component.

Example

 1 <script>
 2     var uri = "http://w3schools.com/my test.asp?name=ståle&car=saab";
 3     var uri_enc = encodeURIComponent(uri);
 4     var uri_dec = decodeURIComponent(uri_enc);
 5     var res = "Encoded URI: " + uri_enc + "<br>" + "Decoded URI: " + uri_dec;
 6     document.write(res);
 7 </script>
 8 // Result
 9 Encoded URI: http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab
10 Decoded URI: http://w3schools.com/my test.asp?name=ståle&car=saab

The different between encodeURI() and encodeURIComponent()

encodeURI()

Use encodeURI when you want a working URL. Make this call:

encodeURI("http://www.google.com/a file with spaces.html")

to get:

http://www.google.com/a%20file%20with%20spaces.html

Don't call encodeURIComponent since it would destroy the URL and return

http%3A%2F%2Fwww.google.com%2Fa%20file%20with%20spaces.html

encodeURIComponent()

Use encodeURIComponent when you want to encode a URL parameter.

param1 = encodeURIComponent("http://xyz.com/?a=12&b=55")

Then you may create the URL you need:

url = "http://domain.com/?param1=" + param1 + "&param2=99";

And you will get this complete URL:

http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%Ffa%3D12%26b%3D55&param2=99

TOOL: text converter

原文地址:https://www.cnblogs.com/hzj680539/p/5082383.html