Borislav Hadzhiev
Thu Nov 18 2021·2 min read
Photo by Alexander Popov
To check if a url has query parameters, call the includes()
method on the
string, passing it a question mark as a parameter, e.g. str.includes('?')
. If
the url contains query parameters, the includes
method will return true
,
otherwise false
is returned.
const url = 'https://example.com?page=10&limit=5'; function hasQueryParams(url) { return url.includes('?'); } // 👇️ true console.log(hasQueryParams('https://example.com?page=10&limit=5')); // 👇️ false console.log(hasQueryParams('https://example.com'));
We created a reusable function that takes a URL string and checks whether it contains query parameters.
The String.includes method allows us to check if a substring is contained in a string.
If the string contains a question mark, we can conclude that it has query parameters.
The includes
method returns a boolean result:
true
if the substring is contained in the stringfalse
if it isn'tAn alternative approach would be use the indexOf()
method.
To check if a url has query parameters, call the indexOf()
method on the
url, passing it a question mark, and check if the result is not equal to -1
,
e.g. url.indexOf('?') !== -1
. The indexOf
method will return -1
if the
string contains no query parameters.
const url = 'https://example.com?page=10&limit=5'; function hasQueryParams(url) { return url.indexOf('?') !== -1; } // 👇️ true console.log(hasQueryParams('https://example.com?page=10&limit=5')); // 👇️ false console.log(hasQueryParams('https://example.com'));
The String.indexOf method allows us to check if the string contains a question mark.
-1
if the substring is not contained in the string.We used the strict equality (===) operator to check if the indexOf
method does
not return -1
.
includes
method as it is more direct and intuitive.