The has()
method of the URLSearchParams
interface returns a boolean value that indicates whether the specified parameter is in the search parameters.
A parameter name and optional value are used to match parameters. If only a parameter name is specified, then the method will return true
if any parameters in the query string match the name, and false
otherwise. If both a parameter name and value are specified, then the method will return true
if a parameter matches both the name and value.
has(name)
has(name, value)
This example shows how to check if the query string has any parameters with a particular name.
const url = new URL("https://example.com?foo=1&bar=2&foo=3");
const params = new URLSearchParams(url.search);
log(`bar?:\t${params.has("bar")}`);
log(`bark?:\t${params.has("bark")}`);
log(`foo?:\t${params.has("foo")}`);
The log below shows whether the parameters bar
, bark
, and foo
, are present in the query string.
This example shows how to check whether the query string has a parameter that matches both a particular name and value.
const url = new URL("https://example.com?foo=1&bar=2&foo=3");
const params = new URLSearchParams(url.search);
log(`bar=1?:\t${params.has("bar", "1")}`);
log(`bar=2?:\t${params.has("bar", "2")}`);
log(`foo=4?:\t${params.has("foo", "4")}`);
Only the second value above should be true
, as only the parameter name bar
with value 2
is matched.
If your browser does not support the value
option the method will match on the name, and all the results should be true
.