window.location以及拆分uri

1.window.location

window.location 只读属性,返回一个 Location 对象,其中包含有关文档当前位置的信息(window.location : 所有字母必须小写)
当在开发者工具中输入window.location时,会显示相应的Uri的信息,如图所示:
在这里插入图片描述
程序员在日常开发时,有时候会获取Uri内部字段对应信息,这个很有用
详细介绍请参考:MDN关于window.location的解释

2.拆分Uri

(1) 正则表达式拆分

 function parseUrl(url) {
    
    
    let result = [];
    let keys = ['href', 'origin', 'protocol', 'host',
                'hostname', 'port', 'pathname', 'search', 'hash'];
    let i;
    let regExp = /(([^:]+:)\/\/(([^:\/\?#]+)(:\d+)?))(\/[^?#]*)?(\?[^#]*)?(#.*)?/;
    let match = regExp.exec(url);
    if (match) {
    
    
        for (i = keys.length - 1; i >= 0; --i) {
    
    
            result[keys[i]] = match[i] ? match[i] : '';
        }
    }
    return result;
}
parseUrl("http://baidu.com.cn:21199/contentListener");

(2) new URL()解析对应地址

const uri = new URL(http://baidu.com.cn:21199/contentListener)
// console.log(uri)时就可以发现其中包含uri所对应的相关字段信息,非常简单

猜你喜欢

转载自blog.csdn.net/weixin_45680024/article/details/126293581