巧用正则和document.location.search获取URL参数的值

  要获取当前页面URL的参数,可能大家第一个想到是使用 window.location.href 或者是document.location.href ,获取结果诸如http://www.xxx.com/?aa=xx&bb=xx ;但是其实我们需要的只是:?aa=xx&bb=xx。这种形式可以使用 document.location.search 这个属性获取。

如果我想要获取该URL后面参数aa的值该怎么弄呢?常见的方式可能是这样:

function( param ){
var url = window . location . toString ();
url
= url . split ('?' );
if (typeof (url [ 1 ]) == 'string' ) {
url
= url [ 1 ]. split ('&' );
for (i = 0 ;i < url . length ;i ++ )
{
s
= url [ i ]. split ("=" );
if( s[0 ] == "param" ) return s[1];
}
}
return null;
}

改用document.location.search和正则获取参数将使代码更加简洁:

function getParameter (sProp )
{
var re = new RegExp (sProp + "=([^\&]*)" , "i" );
var a = re . exec (document . location . search );
if (a == null )
return null ;
return a [ 1 ];
};
posted @ 2011-05-27 14:42  winxp_520  阅读(3767)  评论(0编辑  收藏  举报