使用DOM中的a标签解析url

蚊子前端博客
发布于 2015-11-28 07:00
在以前我们需要解析一个url时,通常会采用正则表达式或者字符串分割的方式来获取想要的部分,不过这里只需要使用a标签就能解析出各种字段

当我们想要解析当前页面的url时,可以使用window.location中提供的各种方法,比如一个页面的地址是这样的:

COPYHTML

http://www.xiabingbao.com:80/javascript/2015/11/28/javascript-a-parse-url/?from=google&v=1.2#hash

那么我们在当前页面下的js里,就可以这样获取url中的各个部分:

  • window.location.href : 整个完整的url

  • window.location.protocol : url的协议(http:或https:等),当前例子返回 http:

  • window.location.host : url的主机地址,当前例子返回 www.xiabingbao.com

  • window.location.port : url的端口号,若采用默认的80端口(即使手动添加),则返回空字符串,当前例子返回 ""

  • window.location.pathname : url的路径部分,当前例子返回 /javascript/2015/11/28/javascript-a-parse-url/

  • window.location.search : url的查询参数部分(返回带有问号),当前例子返回 ?from=google&v=1.2

  • window.location.hash : url的锚点部分,当前例子返回 #hash

但是,如果分析的不是当前页面的地址,而是一个变量中的值,那我们应该怎么办呢?这里我们可以借助a标签来实现解析url的功能。

COPYJAVASCRIPT

// 创建一个额外的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<len;i++) { if (!seg[i]) { continue; } s = seg[i].split('='); ret[s[0]] = s[1]; } return ret; })(), file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1], hash: a.hash.replace('#',''), path: a.pathname.replace(/^([^\/])/,'/$1'), relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1], segments: a.pathname.replace(/^\//,'').split('/') }; }

使用方式:

COPYJAVASCRIPT

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'

获取到的数据与window.location的数据格式很像。从源代码中可以看出,通过DOM来解析url的原理是:首先,创建a(链接)对象,通过把参数url赋值给a的href属性,然后,通过操作a元素的DOM属性,进一步获取链接的更多信息。在这当中,也使用正则表达式来辅助获取各项值。

标签:
阅读(826)

公众号:

qrcode

微信公众号:前端小茶馆

公众号:

qrcode

微信公众号:前端小茶馆