獲取url參數 牛客

題目描述


獲取 url 中的參數

  1. 指定參數名稱,返回該參數的值 或者 空字符串
  2. 不指定參數名稱,返回全部的參數對象 或者 {}
  3. 如果存在多個同名參數,則返回數組

示例

輸入
http://www.nowcoder.com?key=1&key=2&key=3&test=4#hehe key
輸出
[1, 2, 3]

來源:獲取 url 中的參數

解法:

  • 使用split方法分割字符串得到參數序列數組[ 'key=1', 'key=2', 'key=3', 'test=4' ]
  • 設置一個對象以鍵值對的方式存數據,對重複出現的數據轉換爲數組
  • 判斷是否含有sKey,沒有則輸出整個對象,有則判斷res[sKey],爲空則輸出空字符串'',不爲空輸出res[sKey]
function getUrlParam(sUrl, sKey) {
    let res = {};
    let params = sUrl.split('?')[1].split('#')[0].split('&');
    console.log(params);//[ 'key=1', 'key=2', 'key=3', 'test=4' ]
    /* 提取鍵值對存到對象 */
    params.forEach(v => {
        let [key, val] = v.split('=');
        if (res[key])
            res[key] = [...res[key], val];
        else
            res[key] = val;
    })
    /* sKey爲空直接返回對象 */
    if (sKey === undefined) return res;
    else {
        if (res[sKey] === undefined) return '';
        else return res[sKey];
    }
}

另外還可以使用replace結合正則匹配獲取鍵值對實現

function getUrlParam(sUrl, sKey) {
    let res = {};
    sUrl.replace(/\??(\w+)=(\w+)&?/g, (str, key, val) => {
        if (res[key])//值不止一個則轉換爲數組
            res[key] = [...res[key], val];
        else
            res[key] = val;
    })
    if (sKey === undefined) {
        return res;
    } else {
        if (res[sKey] === undefined) return '';
        else return res[sKey];
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章