从网址字符串获取参数值

从网址字符串获取参数值

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

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不会给出期望的结果。请原谅如果已经有答案了。我找不到

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

最佳答案

假设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"]);

关于javascript - 从网址字符串获取参数值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56788874/

10-12 13:14