原生JS去解析地址栏的链接?超好用的解决办法

在做SPA应用程序的时候,往往需要通过地址栏链接的 hash 值来进行业务逻辑:

<script type="text/javascript">
//file:///C:/Users/Administrator/Desktop/angularjs/domo/20.ng.html#baidu
console.log(window.location);
//结果
//Location {hash: "#baidu", search: "", pathname: "/C:/Users/Administrator/Desktop/angularjs/domo/20.ng.html", port: "", hostname: ""…}
</script>

当页面发生点击,请求发生hash值改变的情况:

<script type='text/javascript' >
(function(window){
    window.addEventListener('hashchange',function(e){
        //拿到地址栏的地址
        console.log(window.location.href);
        //拿到地址栏的hash值
        console.log(window.location.hash);
        var oHash = window.location.hash;
        switch(oHash){
            case '#/index/':
                console.log('index');
            case '#case':
                console.log('case');
        };
    });
})(window);
</script>

 

通过 a 链接的方式通过解析地址栏的URL:

最快捷最方便的方式去解析一个 url 地址,是通过 a 标签的方式去解析

<script type="text/javascript">
/*可以通过 window.location 拿到所有URL的所有信息: -->
//https://www.baidu.com:8080/aaa/1.html?id=10#name
protocol: https
host: www.baidu.com:8080
port: 8080
pathname: /aaa/1.html
search: ?id=10
hash: #name*/
var url = "https://www.baidu.com:8080/aaa/1.html?id=10#name";
var aLink = document.createElement('a');
aLink.href = url;
//打印出一个标签<a href="https://www.baidu.com:8080/aaa/1.html?id=10#name"></a>
//使用json遍历(一定是大写的JSON)
//console.log(JSON.stringify({id:1,name:'张三',age:'18'}));
//打印出 {"id":1,"name":"张三","age":"18"}
//JSON 要求键一定是用双引号引起来,json就是一种用字符串描述对象的方式
console.log(aLink.hostname);
console.log(aLink.port);
console.log(aLink.pathname);
console.log(aLink.search);
console.log(aLink.hash);
</script>

除了 a 标签的解析方法,还有字符串的方法,还有通过正则的方式去解析;

正则表达式:
http://tool.oschina.net/regex

 

posted @ 2017-07-20 00:36  帅到要去报警  阅读(1484)  评论(0编辑  收藏  举报