javascript 对象的方式解析url地址参数

看到一个知识点,比如说给一个 url参数,让其解析里面的各个参数,以前我都是通过字符串分割来实现的。但是通过这样的方式比较麻烦,而且操作字符串容易出错。今天看到了一个更有效更快速的方式,就是通过对象来解析的。

比如我们的url是:https://www.baidu.com:8080/aaa/1.html?id=1&key=test 我们现在来通过对象的方式解析。截取字符串都不用说了。

(function(window){
            
            // 需要解析的 url 地址
            var url = "https://www.baidu.com:8080/aaa/1.html?id=1&key=test#ffff";
            
            // 创建以个a标签
            var link = window.document.createElement("a");

            // 给 href 赋值
            link.href = url; 
            console.log("protocol:"+link.protocol);
            console.log("host:"+link.host);
            console.log("hostname:"+link.hostname);
            console.log("port:"+link.port);
            console.log("pathname:"+link.pathname);
            console.log("search:"+link.search);
            console.log("hash:"+link.hash);

        })(window);  

 运行后:

猜你喜欢

转载自www.cnblogs.com/changsen-wang/p/9459336.html
今日推荐