欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js url正则解析

程序员文章站 2022-07-13 11:52:24
...

1.正则

/^(?:(\w+):\/\/)?(?:(\w+):?(\w+)[email protected])?([^:\/\?#]+)(?::(\d+))?(\/[^\?#]+)?(?:\?([^#]+))?(?:#(\w+))?/

2.代码示例

var pattern = /^(?:(\w+):\/\/)?(?:(\w+):?(\w+)[email protected])?([^:\/\?#]+)(?::(\d+))?(\/[^\?#]+)?(?:\?([^#]+))?(?:#(\w+))?/;
var url = 'http://username:[email protected]:1234/artical/js/index.php?key1=js&key2=css#anchor';
var result = pattern.exec(url);

3.返回结果

数组类型 array
- arr[0] 源url
- arr[1] url的协议【http or https】
- arr[2] host中若包含key:value的形式的key,【通常没有为undefined】
- arr[3] host中若包含key:value的形式的value, 【通常没有为undefined】
- arr[4] host地址 【www.baidu.com or localhost or 192.168.0.1】
- arr[5] 端口号port 【8080 or 1234】
- arr[6] path值,接口地址【/api/v1/getData or /2017-10-27/store/pen.html】
- arr[7] url参数字符串 【name=jyjin&age=18】
- arr[8] hash路由,锚点。#号的值 【锚点id or 路由参数】

[
"http://username:[email protected]:1234/artical/js/index.php?key1=js&key2=css#anchor", 
"http", 
"username", 
"password", 
"www.bbs0101.com", 
"1234", 
"/artical/js/index.php", 
"key1=js&key2=css", 
"anchor", 
index: 0, 
input: "http://username:[email protected]:1234/artical/js/index.php?key1=js&key2=css#anchor"
]

4.封装使用

/**
 * @param url
 * @return 模拟location对象
 * - href
 * - hash
 * - host
 * - hostname
 * - origin
 * - pathname
 * - prot
 * - protocol
 * - search
 * 
 * 源返回对象
 * - arr[0] 源url 
 * - arr[1] url的协议                              【http or https】 
 * - arr[2] host中若包含key:value的形式的key        【通常没有为undefined】 
 * - arr[3] host中若包含key:value的形式的value      【通常没有为undefined】 
 * - arr[4] host地址。                             【www.baidu.com or localhost or 192.168.0.1】 
 * - arr[5] 端口号port                             【8080 or 1234】 
 * - arr[6] path值,接口地址                        【/api/v1/getData or /2017-10-27/store/pen.html】 
 * - arr[7] url参数字符串。                         【name=jyjin&age=18】 
 * - arr[8] hash路由,锚点。#号的值.                 【锚点id or 路由参数】
 */
exports.locationUrl = function (url) {
    var pattern = /^(?:(\w+):\/\/)?(?:(\w+):?(\w+)[email protected])?([^:\/\?#]+)(?::(\d+))?(\/[^\?#]+)?(?:\?([^#]+))?(?:#(\w+))?/;
    var arr = pattern.exec(url);

    var hostname = arr[4];
    var port = arr[5];
    var protocol = arr[1] + ':';
    var host = port ? hostname + ':' + port : hostname;
    var href = arr[0];
    var origin = protocol + '//' + host;
    var hash = '#' + arr[8];
    var hostnameKey = arr[2];
    var hostnameValue = arr[3];
    var pathname = arr[6];
    var search = '?' + arr[7];
    return {
        hash: hash,
        host: host,
        hostname: hostname,
        href: href,
        origin: origin,
        pathname: pathname,
        port: port,
        protocol: protocol,
        search: search,
        hosenameKey: hostnameKey,
        hostnameValue: hostnameValue
    }
}

参考【http://www.bbs0101.com/archives/130.html