I’m working on a tool which takes the value parameters in the URL and does a few things with them.
My issue is, I can’t seem to use document.location to show the specific value that I’m after, for example:
www.examplesite.com?yourname=gilgilad
I want to use document.location.search
and put it in a var, I need that var's value to be "gilgilad".
Is this even possible using location.search
?
As of 2025, there're already better options, namely URLSearchParams()
, which you can also convert to an object using Object.fromEntries()
. The solution becomes trivial.
Below couple of no-URLSearchParams approaches, in case you need one or two. In both cases I convert query params to an object step by step, which is useful in case you would need to convert it to JSON.
new Map()
approach (thanks @Stephen from comments)
const url = "example.com/?a=1&b=2&c=3".split("?")[1];
// yields an array of "a=1", "b=2", "c=3"
let key_value_pairs = url.split("&");
// or: key_value_pairs =
// location.search.slice(1).split("&");
// yields an array of [a, 1], [b, 2], [c, 3]
let key_value_arrays = key_value_pairs.map((pair) => pair.split("="));
// converts to Map and then to Object {a: 1, b: 2, c: 3}:
let obj = Object.fromEntries(
new Map(key_value_arrays)
)
console.log(obj);
//examples
console.log(obj.a, obj.b, obj.c)
No-Map approach:
const url = "example.com/?a=1&b=2&c=3";
// yields an array of "a=1", "b=2", "c=3"
let key_value_pairs = url.split("?")[1].split("&");
// or: key_value_pairs =
// location.search.slice(1).split("&");
// yields an array of [a, 1], [b, 2], [c, 3]
let key_value_arrays = key_value_pairs.map((pair) => pair.split("="));
// converts to {a: 1}, {b: 2}, {c: 3}
let array_of_objects = key_value_arrays.map((pair) => (
{ [pair[0]] : pair[1] }
))
// flattens to {a: 1, b: 2, c: 3}
let obj = Object.assign({}, ...array_of_objects);
console.log(obj)
//examples
console.log(obj.a, obj.b, obj.c)
Both of these solutions can be "compressed" to more compact but less readable versions.
In case of Map approach, if you have no need in getting result as an object, you could just settle on new Map(key_value_pairs)
and then use get("param_name")
. If you're interested in comparison between Map and Object, you can find it there.