当我们想要解析当前页面的url时,可以使用 那么我们在当前页面下的js里,就可以这样获取url中的各个部分: 但是,如果分析的不是当前页面的地址,而是一个变量中的值,那我们应该怎么办呢?这里我们可以借助a标签来实现解析url的功能。 使用方式: 获取到的数据与window.location的数据格式很像。从源代码中可以看出,通过DOM来解析url的原理是:首先,创建a(链接)对象,通过把参数url赋值给a的href属性,然后,通过操作a元素的DOM属性,进一步获取链接的更多信息。在这当中,也使用正则表达式来辅助获取各项值。window.location
中提供的各种方法,比如一个页面的地址是这样的:http://www.xiabingbao.com:80/javascript/2015/11/28/javascript-a-parse-url/?from=google&v=1.2#hash
// 创建一个额外的a标签
function parseURL(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':',''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^\?/,'').split('&'),
len = seg.length, i = 0, s;
for (;i
var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
myURL.file; // 'index.html'
myURL.hash; // 'top'
myURL.host; // 'abc.com'
myURL.query; // '?id=255&m=hello'
myURL.params; // Object = { id: 255, m: hello }
myURL.path; // '/dir/index.html'
myURL.segments; // Array = ['dir', 'index.html']
myURL.port; // '8080'
myURL.protocol; // 'http'
myURL.source; // 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'
版权属于:
加速器之家
作品采用:
《
署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
》许可协议授权
评论