从网址字符串获取参数值

时间:2019-06-27 10:17:39

标签: javascript jquery

我需要从网址字符串获取参数值

http://example.com/admin/param1/value1/param2/value2

我已经使用它做到了:

url.split('/param1/')[1].split('/')[0].replace(/\/$/, '');

但是有没有更清洁的选择?像这样吗?

var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);

searchParams在这种情况下无法获得理想的结果。请原谅如果已经有答案了。我找不到。

在将其标记为重复之前,请仔细阅读该问题。

1 个答案:

答案 0 :(得分:1)

假设URL中始终包含/admin/,则可以这样操作:

var testUrls = [
    "http://example.com/admin/param1/value1/param2/value2",
    "http://example.com/admin/name/John/age/50/paramWithNoVal",
];

for (var i = 0; i < testUrls.length; i++) {
    var url        = testUrls[i];
    var paramArray = url.split("/admin/")[1].split("/");
    var paramObj   = {};

    for (var x = 0; x < paramArray.length; x++) {
        // i is even - assume this is a param name
        if (x % 2 === 0) {
            paramObj[paramArray[x]] = paramArray[x + 1] || null;
        }
    }

    console.log(paramObj);
}

编辑:作为功能:

function getUrlParams(url) {
    var paramArray = url.split("/admin/")[1].split("/");
    var paramObj   = {};

    for (var x = 0; x < paramArray.length; x++) {
        if (x % 2 === 0) {
            paramObj[paramArray[x]] = paramArray[x + 1] || null;
        }
    }

    return paramObj;
}

var url    = "http://example.com/admin/param1/value1/param2/value2";
var params = getUrlParams(url);

console.log(params["param1"]);
console.log(params["param2"]);