Check if a URL has Query Parameters in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if a URL has Query Parameters #

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.

index.js
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 if 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, then it has query parameters.

The includes method returns a boolean result:

  • true if the substring is contained in the string
  • false if it isn't

An alternative approach would be use the indexOf() method.

Check if a URL has Query Parameters using indexOf #

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.

index.js
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.

The method returns the index of the first occurrence of the provided substring, or -1 if the substring is not contained in the string.

We used the strict equality (===) operator to check if the indexOf method doesn't return -1.

Which approach you pick is a matter of personal preference. I'd go with the includes method as it is more direct and intuitive.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.