您的位置:首页 > Web前端 > javascript > 正文

escape()、encodeURI()、encodeURIComponent()区别

更多 时间:2014-9-24 类别:Web前端 浏览量:753

escape()、encodeURI()、encodeURIComponent()区别

escape()、encodeURI()、encodeURIComponent()区别

一、escape()

1、escape 方法对所有空格、标点、重音符号以及其他非 ASCII 字符都用 %xx 编码代替,其中 xx 等于表示该字符的十六进制数。例如,空格返回的是 "%20" 。

2、字符值大于 255 的以 %uxxxx 格式存储。

 

 

二、encodeURI()

1、encodeURI 方法只将URI中的空格和非AscII字符进行编码,编码后的URI可以正常访问(ajax中文问题可以使用encodeURI对url进行编码)

2、该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码:;/?:@&=+$,#

 

 

三、encodeURIComponent()

1、encodeURIComponent  方法除了将所有的非ASCII字符编码外,还将一些特殊字符进行编码,如?#:,&等,编码后的URI不可访问。

2、请注意,如果该字符串代表一个路径,例如 /folder1/folder2/default.html,其中的斜杠也将被编码。这样一来,当该编码结果被作为请求发送到 web 服务器时将是无效的。

 

 

四、escape()、encodeURI()、encodeURIComponent()实例

 

  •  
  • JScript 代码   复制
  • 
    var url = 'http://www.studyofnet.com/news/617.html?a=TEST1&b=hello world#'; 
    var results = ['URI: ' + url]; 
    // escape
    results.push('escape: ' + escape(url));
    // encodeURI
    results.push('encodeURI: ' + encodeURI(url));
    // encodeURIComponent
    results.push('encodeURIComponent: ' + encodeURIComponent(url)); 
    document.write(results.join(''));
     
    /*
    URI: http://www.studyofnet.com/news/617.html?a=TEST1&b=hello world#
    
    escape: http%3A//www.studyofnet.com/news/617.html%3Fa%3DTEST1%26b%3Dhello%20world%23
    
    encodeURI: http://www.studyofnet.com/news/617.html?a=TEST1&b=hello%20world#
    
    encodeURIComponent: http%3A%2F%2Fwww.studyofnet.com%2Fnews%2F617.html%3Fa%3DTEST1%26b%3Dhello%20world%23
    
    */
    
    		
  •  

    标签:URL编码解码