手机
当前位置:查字典教程网 >编程开发 >正则表达式 >用Javascript正则实现url链接的解析类
用Javascript正则实现url链接的解析类
摘要:用Javascript解析链接(URL)是一个常见的需求,本文介绍了一个非常健全的用Javascript写的链接(URL)解析类,他可以准确...

用Javascript解析链接(URL)是一个常见的需求,本文介绍了一个非常健全的用Javascript写的链接(URL)解析类,他可以准确获取一个完整的URL中每个部分的内容,包括协议、URL中包含的用户名和密码、主机名、端口、路径名、参数、锚点(FragmentAnchor)等信息。

if (typeof Poly9 == 'undefined') { var Poly9 = {}; } Poly9.URLParser = function(url) { this._fields = { 'Username' : 4, 'Password' : 5, 'Port' : 7, 'Protocol' : 2, 'Host' : 6, 'Pathname' : 8, 'URL' : 0, 'Querystring' : 9, 'Fragment' : 10 }; this._values = {}; this._regex = null; this.version = 0.1; this._regex = /^((w+)://)?((w+):?(w+)?@)?([^/?:]+):?(d+)?(/?[^?#]+)???([^#]+)?#?(w*)/; for(var f in this._fields) { this['get' + f] = this._makeGetter(f); } if (typeof url != 'undefined') { this._parse(url); } } Poly9.URLParser.prototype.setURL = function(url) { this._parse(url); } Poly9.URLParser.prototype._initValues = function() { for(var f in this._fields) { this._values[f] = ''; } } Poly9.URLParser.prototype._parse = function(url) { this._initValues(); var r = this._regex.exec(url); if (!r) throw "DPURLParser::_parse -> Invalid URL"; for(var f in this._fields) if (typeof r[this._fields[f]] != 'undefined') { this._values[f] = r[this._fields[f]]; } } Poly9.URLParser.prototype._makeGetter = function(field) { return function() { return this._values[field]; } } var url = 'http://user:password@www.jb51.net:1234/test/test.asp?id=1#test'; var p = new Poly9.URLParser(url); document.write("URL: " + url + "

"); document.write("解析结果如下:

"); document.write("协议: " + p.getProtocol() + "

"); document.write("用户: " + p.getUsername() + "

"); document.write("密码: " + p.getPassword() + "

"); document.write("主机: " + p.getHost() + "

"); document.write("端口: " + p.getPort() + "

"); document.write("路径: " + p.getPathname() + "

"); document.write("查询字符串: " + p.getQuerystring() + "

"); document.write("锚点: " + p.getFragment() + "

");

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

【用Javascript正则实现url链接的解析类】相关文章:

Javascript正则表达式测试网页

使用正则表达式 exec 获取字符串中的汉字

javascript下正则匹配百分比的代码

Java正则表达式基础入门知识

使用正则表达式匹配[***]样式的字符串

javascript用正则表达式把1234567890替换为abcdefghij

js用正则表达式控制价格输入实现代码

asp下正则实现URL自动链接的一个函数

如何用javascript正则表达式验证身份证号码是否合法

javascript利用正则快速找出两个字符串的不同字符

精品推荐
分类导航