Skip to content
Advertisement

How can I get query string values in JavaScript?

Is there a plugin-less way of retrieving query string values via jQuery (or without)?

If so, how? If not, is there a plugin which can do so?

Advertisement

Answer

Update: Jan-2022

Using Proxy() is faster than using Object.fromEntries() and better supported

JavaScript

Update: June-2021

For a specific case when you need all query params:

JavaScript

Update: Sep-2018

You can use URLSearchParams which is simple and has decent (but not complete) browser support.

JavaScript

Original

You don’t need jQuery for that purpose. You can use just some pure JavaScript:

JavaScript

Usage:

JavaScript

NOTE: If a parameter is present several times (?foo=lorem&foo=ipsum), you will get the first value (lorem). There is no standard about this and usages vary, see for example this question: Authoritative position of duplicate HTTP GET query keys.

NOTE: The function is case-sensitive. If you prefer case-insensitive parameter name, add ‘i’ modifier to RegExp

NOTE: If you’re getting a no-useless-escape eslint error, you can replace name = name.replace(/[[]]/g, '\$&'); with name = name.replace(/[[]]/g, '\$&').


This is an update based on the new URLSearchParams specs to achieve the same result more succinctly. See answer titled “URLSearchParams” below.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement