0

I need to obtain parameter values from url string

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

I did it already using this:

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

But is there any cleaner alternative ? Something like this ?

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 don't give desired results in this case. Pardon if there is already an answer out there. I couldn't find.

Please read the question carefully before marking it as duplicate.

6
  • 2
    Not a duplicate. Please read the question carefully. Commented Jun 27, 2019 at 10:24
  • You could use PURL (github.com/allmarkedup/purl) but I guess your single-liner is faster. Commented Jun 27, 2019 at 10:26
  • @CarstenLøvboAndersen it dont work for the string http://example.com/admin/param1/value1/param2/value2 Commented Jun 27, 2019 at 10:29
  • @shreyasdharav your question is missing some information, the parameter you wish to get, is it always at one specific location in the url ? or Commented Jun 27, 2019 at 10:40
  • searchParams don't give desired results in this case? Can you elaborate further on that? I think it should @sh Commented Jun 27, 2019 at 10:49

1 Answer 1

1

Assuming the URL always has /admin/ in it, you could do it like so:

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);
}

Edit: as a function:

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.