JS获得url变量值

2017-05-15  本文已影响0人  1223153132

javaScript 客户端中获取url的传参数

GetQueryString(name) 

name 为参数的变量

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;

}

例子:

url: a.html?id=123

console.log(GetQueryString("id"));

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;

}

输出:123

延伸:

用该属性获取页面 URL 地址:

window.location 对象所包含的属性

属性描述

hash :从井号 (#) 开始的 URL(锚)

host : 主机名和当前 URL 的端口号

hostname : 当前 URL 的主机名

href : 完整的 URL

pathname : 当前 URL 的路径部分

port : 当前 URL 的端口号

protocol : 当前 URL 的协议

search : 从问号 (?) 开始的 URL(查询部分)

console.log(window.location.search);  输出 ?id=123

console.log(window.location.search.substr);  输出id=123 

match(reg) :表示为 正则表达式 

上一篇下一篇

猜你喜欢

热点阅读