Check if a URL has Query Parameters in JavaScript

avatar

Borislav Hadzhiev

Thu Nov 18 20212 min read

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 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 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 does not 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.
Use the search field on my Home Page to filter through my more than 1,000 articles.