您的位置:首页 > Web前端 > JavaScript

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

2015-12-28 14:14 876 查看
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

<script>
var uri = "my test.asp?name=ståle&car=saab";
var enc = encodeURI(uri);
var dec = decodeURI(enc);
var res = "Encoded URI: " + enc + "<br>" + "Decoded URI: " + dec;
document.write(res);
</script>
// Result
Encoded URI: my%20test.asp?name=st%C3%A5le&car=saab
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

<script>
var uri = "http://w3schools.com/my test.asp?name=ståle&car=saab";
var uri_enc = encodeURIComponent(uri);
var uri_dec = decodeURIComponent(uri_enc);
var res = "Encoded URI: " + uri_enc + "<br>" + "Decoded URI: " + uri_dec;
document.write(res);
</script>
// Result
Encoded URI: http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab
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 + "¶m2=99";


And you will get this complete URL:

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


TOOL: text converter
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: