JS截取URL参数
<html> <head> <meta charset="utf-8"> <title>截取url参数</title> <script type="text/javascript"> /** * getParamVal 基础函数 * 获取url中参数的key和value * 返回json对象 */ function getParamVal() { var params = {}; if ( location.search !== '' ) { var arr = location.search.substring(1).split('&'); for ( var i = 0, iLen = arr.length; i < iLen; i ++ ) { var aTmp = arr[i].split('='), value = decodeURIComponent(aTmp[1]), numberVal = Number(value); //处理数字 if ( typeof numberVal === 'number' && numberVal === numberVal ) { value = numberVal; } //处理布尔值 if ( value === 'true' || value === 'false' ) { value = value === 'true'; } params[aTmp[0]] = value; } } return params; } //用法:url html?id=5&state=5asdfasede&viral=2 /* var params = getParamVal(); alert(params['id']); */ /** * 智能截取url参数中的数值 * getParamNumber 获取参数值中从第n位开始截取len长度的数字,当遇到非数字类型时终止截取 * 注:依赖 getParamVal 函数 * 返回截取后的数值,number类型 */ function getParamNumber(key, n, len) { var vals = getParamVal()[key], valN = ''; if ( !vals ) return undefined; for ( var i = n; i < len+n; i ++ ) { var iTmp = Number(vals.charAt(i)); if (typeof iTmp == 'number' && iTmp === iTmp) { valN += vals.charAt(i); } else { break; } } return valN ? Number(valN) : undefined; } //用法 url html?state=210.0&openid=520SN6jhUe5gI&id=15524ses alert( getParamNumber('openid', 1, 3) ); </script> </head> <body> </body> </html>