小記--獲取url鍵值

之後會不按期把項目中用到的也是咱們平時開發經常使用的一些方法貼出來,也是一個自我總結的過程

獲取url鍵值是咱們在項目會常常遇到的需求。下面是我在項目中封裝的方法,詳細的說明在代碼都有註釋。html

/**
 * 獲取url鍵值
 * url => [href] | [param]
 * 不填參數則返回JSON 格式全部數據
 */
const urlCodeToObj = url => {
    let u = url || window.location.href
    //判斷url是完整的連接仍是傳入的參數
    if (RegExp(/^((https|http)?:\/\/)/).test(u)) {
        //將url中的空格去掉並匹配'?'後面的參數字符串集合
        const search = u.replace(/^\s+|\s+$/, '').match(/([^?#]*)(#.*)?$/)
        if (!search) {
            search = {}
        }
        //把匹配到的字符串以'&'分割變換成數組形式
        let searchHash = search[1].split('&');
        let paramObj = {} //鍵值對對象集合
        for (let item of searchHash) {
            const pair = item.split('=')
            if (pair[0]) {
                const key = decodeURIComponent(pair[0])
                const value = pair[1]
                if (value != undefined) {
                    value = decodeURIComponent(value)
                }
            }
            //判斷轉化後的paramObj裏面有沒有重複的屬性
            if (key in paramObj) {
                if (paramObj[key] instanceof Array) {
                    //把屬性值變爲數組,將另外的屬性值也存放到數組中去
                    paramObj[key] = [paramObj[key]]
                }
                paramObj[key].push(value)
            } else {
                paramObj[key] = value
            }
        }
        return paramObj
    } else {
        //返回單個屬性值 string
        if (RegExp(/^\w+/).test(u)) {
             //匹配屬性值,好比http://xxx.com/web/page/prodetail.html?num=200&productID=4690&id=100
             //輸入值爲 &productID=4690&,而後進行匹配.
            let reg = new RegExp(`(^|&)${u}=([^&]*)(&|$)`,"i")
            const matchArr = window.location.search.substr(1).match(reg)
            if (matchArr != null) return (matchArr[2])
            return null
        }
    }
}
相關文章
相關標籤/搜索