方法一
源码:
function GetQueryString ( name )
{
var reg = new RegExp ( "(^|&)" + name + "=([^&]*)(&|$)" ) ;
var r = window. location. search. substr ( 1 ) . match ( reg) ;
if ( r!= null ) return unescape ( r[ 2 ] ) ; return null ;
}
使用:
console. log ( GetQueryString ( "参数名1" ) ) ;
console. log ( GetQueryString ( "参数名2" ) ) ;
方法二
源码:
function gup ( name, url ) {
if ( ! url) url = location. href;
name = name. replace ( / [\[] / , "\\\[" ) . replace ( / [\]] / , "\\\]" ) ;
var regexS = "[\\?&]" + name+ "=([^&#]*)" ;
var regex = new RegExp ( regexS ) ;
var results = regex. exec ( url ) ;
return results == null ? null : results[ 1 ] ;
}
使用:
gup ( 'q' , 'hxxp://example.com/?q=abc' )
方法三
源码:
const getURLParameters = url =>
( url. match ( / ([^?=&]+)(=([^&]*)) / g ) || [ ] ) . reduce (
( a, v ) => (
( a[ v. slice ( 0 , v. indexOf ( '=' ) ) ] = v. slice ( v. indexOf ( '=' ) + 1 ) ) , a
) ,
{ }
) ;
使用:
getURLParameters ( 'google.com' ) ;
getURLParameters ( 'http://url.com/page?name=Adam&surname=Smith' ) ;
原文链接
JS获取 URL 链接参数