首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在JavaScript中将URL解析为主机名和路径?

如何在JavaScript中将URL解析为主机名和路径?
EN

Stack Overflow用户
提问于 2018-06-14 10:16:43
回答 2查看 0关注 0票数 0

我想要一个字符串

代码语言:javascript
复制
var a = "http://example.com/aa/bb/"

并将其处理为一个对象

代码语言:javascript
复制
a.hostname == "example.com"

代码语言:javascript
复制
a.pathname == "/aa/bb"
EN

回答 2

Stack Overflow用户

发布于 2018-06-14 19:14:53

代码语言:javascript
复制
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";

parser.protocol; // => "http:"
parser.host;     // => "example.com:3000"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.hash;     // => "#hash"
parser.search;   // => "?search=test"
parser.origin;   // => "http://example.com:3000"
票数 0
EN

Stack Overflow用户

发布于 2018-06-14 19:59:21

代码语言:javascript
复制
function getLocation(href) {
    var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
    return match && {
        href: href,
        protocol: match[1],
        host: match[2],
        hostname: match[3],
        port: match[4],
        pathname: match[5],
        search: match[6],
        hash: match[7]
    }
}

-

代码语言:javascript
复制
getLocation("http://example.com/");
/*
{
    "protocol": "http:",
    "host": "example.com",
    "hostname": "example.com",
    "port": undefined,
    "pathname": "/"
    "search": "",
    "hash": "",
}
*/

getLocation("http://example.com:3000/pathname/?search=test#hash");
/*
{
    "protocol": "http:",
    "host": "example.com:3000",
    "hostname": "example.com",
    "port": "3000",
    "pathname": "/pathname/",
    "search": "?search=test",
    "hash": "#hash"
}
*/

这是正则表达式的细分

代码语言:javascript
复制
var reURLInformation = new RegExp([
    '^(https?:)//', // protocol
    '(([^:/?#]*)(?::([0-9]+))?)', // host (hostname and port)
    '(/{0,1}[^?#]*)', // pathname
    '(\\?[^#]*|)', // search
    '(#.*|)$' // hash
].join(''));
var match = href.match(reURLInformation);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100005395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档