JS動態獲取項目名以及獲取URL地址中的參數

在項目當中咱們可能會遇到例如改變的項目名稱以後,相對應的地址就須要改變,爲了減小工做量,將地址當中的項目名這一塊寫成動態獲取的,那麼最關鍵一點就是我要先獲取它,再進行操做;javascript

知識點整理,話很少說,直接貼代碼:html

獲取項目名:java

function URLPath(msg){
    var pathName = window.document.location.pathname;
    var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return projectName+msg;
}
URLPath();
//pathName爲獲取的整個地址
//projectName爲截取的項目名稱,格式爲(‘/項目名’)
//msg參數爲地址,格式爲('/index.html')

每每咱們URL地址中帶一些不涉及隱私、安全問題的參數是徹底ok的,那麼在這些地址當中,我想在頁面將相對應的參數值獲取到,那該如何應對呢?安全

獲取URL地址參數:  code

function getQueryString(attr){
    var reg = new RegExp('(^|&)'+attr+'=([^&]*)(&|$)');
    var r = window.location.search.substr(1).match(reg);
//            if(r != null){
//                return decodeURI(r[2]);
//            }else{
//                return null;
//            }
    return r == null?null:decodeURI(r[2]);
}
getQueryString();

//參數attr爲相對應屬性名稱,例如:('name')
//unescape()方法ECMAScript v3反對使用,所以用decodeURI() 和 decodeURIComponent()替代,解碼
 
方法總結,便於使用,不喜勿噴…
相關文章
相關標籤/搜索