对URL
编码是常见的事,所以这两个方法应该是实际中要特别注意的。
它们都是编码URL,唯一区别就是编码的字符范围,其中
encodeURI
encodeURI方法不会对下列字符编码 ASCII字母、数字、~!@#$&*()=:/,;?+'
encodeURIComponent
encodeURIComponent方法不会对下列字符编码 ASCII字母、数字、~!*()'
所以encodeURIComponent比encodeURI编码的范围更大。
实际例子来说,encodeURIComponent会把 http://
编码成 http%3A%2F%2F
而encodeURI却不会。
比如1
encodeURI("http://www.baidu.com/some other test");
编码后会变为1
"http://www.baidu.com/some%20other%20test";
其中,空格被编码成了%20。但是如果你用了encodeURIComponent,那么结果变为1
"http%3A%2F%2Fwww.cnblogs.com%2Fsome%20other%20test"
看到了区别吗,连 “/“ 都被编码了,整个URL已经没法用了。