Get Url Query String Parameters

How can I get query string values in JavaScript?

Update: Jan-2022

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

const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
// Get the value of "some_key" in eg "https://example.com/?some_key=some_value"
let value = params.some_key; // "some_value"

Update: June-2021

For a specific case when you need all query params:

const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());

Update: Sep-2018

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

const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');

Original

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

function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

Usage:

// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)

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.

How can I get (query string) parameters from the URL in Next.js?

  • Get it by using the below code in the about.js page:

    Sample Image

// pages/about.js
import Link from 'next/link'
export default ({ url: { query: { name } } }) => (
<p>Welcome to About! { name }</p>
)

How to obtain the query string from the current URL with JavaScript?

Have a look at the MDN article about window.location.

The QueryString is available in window.location.search.

If you want a more convenient interface to work with, you can use the searchParams property of the URL interface, which returns a URLSearchParams object. The returned object has a number of convenient methods, including a get-method. So the equivalent of the above example would be:

let params = (new URL(document.location)).searchParams;
let name = params.get("name");

The URLSearchParams interface can also be used to parse strings in a querystring format, and turn them into a handy URLSearchParams object.

let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);

searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true

The URLSearchParams interface is now widely adopted in browsers (95%+ according to Can I Use), but if you do need to support legacy browsers as well, you can use a polyfill.

Get URL query string parameters

$_SERVER['QUERY_STRING'] contains the data that you are looking for.


DOCUMENTATION

  • php.net: $_SERVER - Manual

Get query string parameters url values with jQuery / Javascript (querystring)

After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!

//Assuming URL has "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

UPDATE : IE is not supported

use this function from an answer below instead of URLSearchParams

$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);

return (results !== null) ? results[1] || 0 : false;
}

console.log($.urlParam('action')); //edit

How can I get query string values in JavaScript?

Update: Jan-2022

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

const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
// Get the value of "some_key" in eg "https://example.com/?some_key=some_value"
let value = params.some_key; // "some_value"

Update: June-2021

For a specific case when you need all query params:

const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());

Update: Sep-2018

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

const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');

Original

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

function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

Usage:

// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)

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.

How can I get parameters from a URL string?

You can use the parse_url() and parse_str() for that.

$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['email'];

If you want to get the $url dynamically with PHP, take a look at this question:

Get the full URL in PHP

How to get parameter value from query string?

React Router v6, using hooks

In react-router-dom v6 there's a new hook named useSearchParams. So with

const [searchParams, setSearchParams] = useSearchParams();
searchParams.get("__firebase_request_key")

you will get "blablabla". Note, that searchParams is an instance of URLSearchParams, which also implements an iterator, e.g. for using Object.fromEntries etc.

React Router v4/v5, without hooks, generic

React Router v4 does not parse the query for you any more, but you can only access it via this.props.location.search (or useLocation, see below). For reasons see nbeuchat's answer.

E.g. with qs library imported as qs you could do

qs.parse(this.props.location.search, { ignoreQueryPrefix: true }).__firebase_request_key

Another library would be query-string. See this answer for some more ideas on parsing the search string. If you do not need IE-compatibility you can also use

new URLSearchParams(this.props.location.search).get("__firebase_request_key")

For functional components you would replace this.props.location with the hook useLocation. Note, you could use window.location.search, but this won't allow to trigger React rendering on changes.
If your (non-functional) component is not a direct child of a Switch you need to use withRouter to access any of the router provided props.

React Router v3

React Router already parses the location for you and passes it to your RouteComponent as props. You can access the query (after ? in the url) part via

this.props.location.query.__firebase_request_key

If you are looking for the path parameter values, separated with a colon (:) inside the router, these are accessible via

this.props.match.params.redirectParam

This applies to late React Router v3 versions (not sure which). Older router versions were reported to use this.props.params.redirectParam.

General

nizam.sp's suggestion to do

console.log(this.props)

will be helpful in any case.

How can I get query parameters from a URL in Vue.js?

According to the docs of route object, you have access to a $route object from your components, which exposes what you need. In this case

//from your component
console.log(this.$route.query.test) // outputs 'yay'


Related Topics



Leave a reply



Submit