js獲取url地址中的每一個參數,方便操作url的hash及正則表達式的方式獲取在url上參數

js獲取url地址中的每一個參數,方便操作url的hash

<html>
    <body>
        <script>
            //location.search; //可獲取瀏覽器當前訪問的url中"?"符後的字串
            function parseURL(url) { 		 
                var a =  document.createElement('a'); 		 
                a.href = url; 		 
                return { 			 
                    source: url, 			 
                    protocol: a.protocol.replace(':',''), 			 
                    host: a.hostname, 			 
                    port: a.port, 			 
                    query: a.search, 			 
                    params: (function(){ 	
                        var ret = {}, 		
                        seg = a.search.replace(/^\?/,'').split('&'), //將該字符串首位的?替換成空然後根據&來分隔返回一個數組	         
                        len = seg.length, i = 0, s; 			     
                        for (;i<len;i++) { 			         
                            if (!seg[i]) { 
                                continue; 
                            } 			         
                            s = seg[i].split('='); 			         
                            ret[s[0]] = s[1]; 			     
                        } 			     
                        return ret; 			 
                    })(), 			 
                    file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1], 			 
                    hash: a.hash.replace('#',''), 			 
                    path: a.pathname.replace(/^([^\/])/,'/$1'),//將該字符串首位不是/的用這個組([^\/])替換,$1代表出現在正則表達式中的第一個()、$2代表出現在正則表達式中的第二個()...			 
                    relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1], 			 
                    segments: a.pathname.replace(/^\//,'').split('/') 		}; 	
                }   		
                var URL = parseURL('http://abc.com:8080/dir/index.html?pid=255&m=hello#top&ab=1'); 	
                // var URL = parseURL('http://localhost:8080/test/mytest/toLogina.ction?m=123&pid=abc'); 	
                console.log('URL.query', URL.query)
                console.log('URL.path', URL.path); 
                console.log('URL.hash', URL.hash); 	
                console.log('URL.params.pid', URL.params.pid); 
        </script>
    </body>
</html>

參考:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace

正則表達式的方式獲取在url上參數

function getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    };
    return null;
 }

unescape函數很好理解,是對URL進行解碼。那麼爲什麼參數值是取r[2]呢?這就涉及到JS中match函數的用法了,查了W3school的文檔,有這樣一句話:如果沒有找到任何匹配的文本, match() 將返回 null。否則,它將返回一個數組,其中存放了與它找到的匹配文本有關的信息。該數組的第 0 個元素存放的是匹配文本,而其餘的元素存放的是與正則表達式的子表達式匹配的文本。這就很好理解了,我們的match匹配返回的r中第0個元素是匹配的文本,後面的元素是正則子表達式匹配的文本。

調用

假設url='https://www.xxx.com?from=1&ch=1' 我們要獲取from的值

var from = getQueryString('from');
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章