JS获取地址栏参数(支持中文)

function GetQueryString(name){
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  decodeURIComponent(r[2]); return null;
}
 
// 调用方法
alert(GetQueryString("参数名"));

 例子:

其实这个写法就是将网上广泛流传的版本修改了一下解码方式:escape → decodeURIComponent

为什么escape不支持中文,而decodeURIComponent能支持中文呢?

那就要讲一下 escape,encodeURI,encodeURIComponent 三者的用法区别了

escape

该方法不会对 ASCII 字母和数字进行编码,也不会对下面这些 ASCII 标点符号进行编码: * @ - _ + . / 

escape() 编码,unescape()解码。

注释:ECMAScript v3 反对使用该方法,应用使用 decodeURI() 和 decodeURIComponent() 替代它。

最关键的是,当你需要对URL编码时,请忘记这个方法,这个方法是针对字符串使用的,不适用于URL。

encodeURI

该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码:  - _ . ! ~ * ' ( )  

该方法不会对URI 中具有特殊含义的 ASCII 标点符号进行转义: ;/?:@&=+$,#

encodeURI() 编码,decodeURI() 解码。

encodeURIComponent

该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 

该方法会对用于分隔 URI 组件的标点符号进行十六进制转换 :;/?:@&=+$,# 

该方法认为它的参数是 URI 的一部分(比如协议、主机名、路径或查询字符串),因此 encodeURIComponent() 函数将转义用于分隔 URI 各个部分的标点符号。

encodeURIComponent() 比encodeURI()编码范围大!
例如: http://
encodeURIComponent()    编码为     http%3A%2F%2F
encodeURI()                    编码为       http://
 
encodeURIComponent() 编码, decodeURIComponent() 解码。
 
 
所以三者的使用场合就知道了!
    
1、如果只是编码字符串,不和URL有半毛钱关系,那么用escape。
 
2、如果你需要编码整个URL,然后需要使用这个URL,那么用encodeURI。
例如
encodeURI("http://www.cnblogs.com/season-huang/some other thing");
编码后会变为
"http://www.cnblogs.com/season-huang/some%20other%20thing";

其中,空格被编码成了%20。但是如果你用了encodeURIComponent,那么结果变为

"http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2Fsome%20other%20thing"

看到了区别吗,连 "/" 都被编码了,整个URL已经没法用了。

3、如果 URI 组件中含有分隔符,比如 ? 和 #,则应当使用 encodeURIComponent() 方法分别对各组件进行编码。

var param = "http://www.cnblogs.com/season-huang/"; //param为参数
param = encodeURIComponent(param);
var url = "http://www.cnblogs.com?next=" + param;
console.log(url) //"http://www.cnblogs.com?next=http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2F"
看到了把,参数中的 "/" 可以编码,如果用encodeURI肯定要出问题,因为后面的/是需要编码的。
 
 
 
原文地址:https://www.cnblogs.com/hcxwd/p/7283408.html