How to Get a Specific Parameter from Location.Search

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.

Get values of parameters from URL

location.search will return all after question mark including it. So there is universal js to get value of the first parameter (even if url has more parameters):

var desire = location.search.slice(1).split("&")[0].split("=")[1]

Example: let's take url http://example.com?name=jon&country=us

  1. location.search will be equal to ?name=jon&country=us
  2. .slice(1) skips the ?, returning the rest of the string.
  3. .split("&")[0] splits it into two strings (name=jon and
    country=us) and takes first one
  4. .split("=")[1] splits name=jon into name and jon and takes the second one. Done!

How to retrieve GET parameters from JavaScript

With the window.location object. This code gives you GET without the question mark.

window.location.search.substr(1)

From your example it will return returnurl=%2Fadmin

EDIT: I took the liberty of changing Qwerty's answer, which is really good, and as he pointed I followed exactly what the OP asked:

function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}

I removed the duplicated function execution from his code, replacing it a variable ( tmp ) and also I've added decodeURIComponent, exactly as OP asked. I'm not sure if this may or may not be a security issue.

Or otherwise with plain for loop, which will work even in IE8:

function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}

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.

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.

Javascript get URL parameter that starts with a specific string

You can use window.location.search to get all parameters after (and including ?) from url. Then it's just a matter of looping through each parameter to check if it match.

Not sure what kind of array you expect for result but here is very rough and basic example to output only matched values in array:

var query = window.location.search.substring(1);
var qsvars = query.split("&");
var matched = qsvars.filter(function(qsvar){return qsvar.substring(0,4) === 'Loc-'});
matched.map(function(match){ return match.split("=")[1]})

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 search window.location.search for specific text?

You could use indexOf()

if(window.location.search.indexOf("gclid=") > -1)

How to get URL parameter using jQuery or plain JavaScript?

Best solution here.

var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;

for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');

if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
return false;
};

And this is how you can use this function assuming the URL is,

http://dummy.com/?technology=jquery&blog=jquerybyexample.

var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');


Related Topics



Leave a reply



Submit