您的位置:首页 > Web前端 > JavaScript

转-Javascript对URL地址解析为对象的方法

2013-05-25 20:08 555 查看
// 对形如http://www.qq.com:80/index.html?key1=1&key2=2&key3=3#hcy的url字符串进行解析,并返回类似location对象的实体对象
var parseUrl = function() {
var pos1, // 保存":"字符的位置(注意是前半部分字符串里的":")
pos2, // 保存"/"字符的位置
pos3, // 保存"?"字符的位置
pos4, // 保存"#"字符的位置
pos5, // 保存":"字符的位置(注意是后半部分字符串里的":")
protocol, // 协议
hostname, // 主机名
port, // 端口
pathname, // 路径
queryStr, // 查询字符串
hash, // 锚标记信息
matchArr,
beforeStr, // 前半部分字符串
afterStr, // 后半部分字符串
queryObj = {}, // 保存查询字符串基于名值对(key=value)的数据对象
url = arguments[0]; // 获取url字符串
matchArr = url ? url.split("//") : alert("请输入url"); // 根据"//"分隔符把字符串分隔成数组的两项
beforeStr = matchArr[0];
afterStr = matchArr[1];

// 获取相应字符位置,注意:当查找的字符串不存在时返回-1
pos1 = beforeStr.indexOf(":");
pos2 = afterStr.indexOf("/");
pos3 = afterStr.indexOf("?");
pos4 = afterStr.indexOf("#");
pos5 = afterStr.indexOf(":");

// 获取协议
protocol = pos1 > -1 ? beforeStr.slice(0, pos1) : "";

// 获取主机名
hostname = pos5 > -1 ? afterStr.slice(0, pos5) : afterStr.slice(0);

// 获取端口,默认为80(输出空字符串),其他正常输出
port = pos5 > -1 ?
pos2 > -1 ?
afterStr.slice(pos5 + 1, pos2) :
afterStr.slice(pos5 + 1) :
"";
port = parseInt(port) === 80 ? "" : port;

// 获取路径,注意对空值进行处理
pathname = pos3 > -1 && (pos2 > -1) ?
afterStr.slice(pos2, pos3) :
pos2 > -1 ?
afterStr.slice(pos2) :
"";

// 获取查询字符串,注意对空值进行处理
queryStr = pos4 > -1 ? (pos3 > -1) && afterStr.slice(pos3, pos4) :
pos3 > -1 ? afterStr.slice(pos3) : "";

hash = pos4 > -1 ? afterStr.slice(pos4) : ""; // 获取锚(存在时直接返回,不存在时返回空字符串)

// 对queryString进行处理
var arr = queryStr ? queryStr.replace(/\?*/,"").split("&") : [],
item,
name,
value;
for (var i = 0; i < arr.length; i++) {
item = arr[i].split("=");
name = item[0], // 获取名值对的名称
value = item[1]; // 获取名值对的值
// 把每一"名值对"构造成数据对象
queryObj[name] = value;
}

// 返回一个包含上述属性的对象
return {
protocol:  protocol,
hostname:  hostname,
port:        port,
pathname:  pathname,
queryStr:  queryStr,
hash: hash,
queryObj: queryObj
};
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: