JavaScript正则表达式匹配网站URL/实现url链接的解析/解析链接中的URL路径

一个完整的 URL 中每个部分的内容,包括协议、URL中包含的用户名和密码、主机名、端口、路径名、参数、锚点(Fragment Anchor)等信息

比如我要对下面的url进行处理

http://user:password@www.jsdaxue.com:8080/test/test.asp?id=1#test

处理的完整代码如下;

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="example">
<div id="example_main">
<script type="text/javascript">
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.jsdaxue.com:8080/test/test.asp?id=1#test';
var p = new Poly9.URLParser(url);
document.write("<strong>URL:</strong> " + url + "<br><br>");
document.write("解析结果如下:<br><br>");
document.write("<strong>协议:</strong> " + p.getProtocol() + "<br>");
document.write("<strong>用户:</strong> " + p.getUsername() + "<br>");
document.write("<strong>密码:</strong> " + p.getPassword() + "<br>");
document.write("<strong>主机:</strong> " + p.getHost() + "<br>");
document.write("<strong>端口:</strong> " + p.getPort() + "<br>");
document.write("<strong>路径:</strong> " + p.getPathname() + "<br>");
document.write("<strong>查询字符串:</strong> " + p.getQuerystring() + "<br>");
document.write("<strong>锚点:</strong> " + p.getFragment() + "<br>");
</script>
</div>
</div>
</body>
</html>

输出的结果如下

URL: http://user:password@www.jsdaxue.com:8080/test/test.asp?id=1#test
解析结果如下:
协议: http
用户: user
密码: password
主机: www.jsdaxue.com
端口: 8080
路径: /test/test.asp
查询字符串: id=1
锚点: test

按照您需要的直接调用就可以了;

~~

未经允许不得转载:WEB前端开发 » JavaScript正则表达式匹配网站URL/实现url链接的解析/解析链接中的URL路径

赞 (0)