Javascript get query param

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

Voting to reopen, the marked duplicate is a request for a library, whereas this question is about getting js code.

19 Answers 19

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.

The first function getQueryStringValue for legacy browsers, doesn’t work for ?foo=bar&foo1=bar1 If we try to fetch value for foo , it returns empty string .

@Pratyush yes I mention that in the answer, with a reference to the more popular and more frequently updated url-search-params-polyfill package.

Use window.location.search to get everything after ? including ?

var url = window.location.search; url = url.replace("?", ''); // remove the ? alert(url); //alerts ProjectID=462 is your case 
decodeURI(window.location.search) .replace('?', '') .split('&') .map(param => param.split('=')) .reduce((values, [ key, value ]) => < values[ key ] = value return values >, <>) 

Good approach. Thanks. A lit bit fix it tho: replace checks the whole(!) string. we need to remove the first char. removing unnecessary loops. Result: window.location.search window.location.search.substr(1) .split(«&») .reduce((acc, param) => < const Javascript get query param = param.split("="); return < . acc, Javascript get query param: value >; >, <>)

If you happened to use Typescript and have dom in your the lib of tsconfig.json , you can do:

const url: URL = new URL(window.location.href); const params: URLSearchParams = url.searchParams; // get target key/value from URLSearchParams object const yourParamValue: string = params.get('yourParamKey'); // To append, you can also leverage api to avoid the `?` check params.append('newKey', 'newValue'); 

You can use this for direct find value via params name.

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

This will add a global function to access to the queryString variables as a map.

// ------------------------------------------------------------------------------------- // Add function for 'window.location.query( [queryString] )' which returns an object // of querystring keys and their values. An optional string parameter can be used as // an alternative to 'window.location.search'. // ------------------------------------------------------------------------------------- // Add function for 'window.location.query.makeString( object, [addQuestionMark] )' // which returns a queryString from an object. An optional boolean parameter can be // used to toggle a leading question mark. // ------------------------------------------------------------------------------------- if (!window.location.query) < window.location.query = function (source) < var map = <>; source = source || this.search; if ("" != source) < var groups = source, i; if (groups.indexOf("?") == 0) < groups = groups.substr(1); >groups = groups.split("&"); for (i in groups) < source = groups[i].split("=", // For: xxx=, Prevents: [xxx, ""], Forces: [xxx] (groups[i].slice(-1) !== "=") + 1 ); // Key i = decodeURIComponent(source[0]); // Value source = source[1]; source = typeof source === "undefined" ? source : decodeURIComponent(source); // Save Duplicate Key if (i in map) < if (Object.prototype.toString.call(map[i]) !== "[object Array]") < map[i] = [map[i]]; >map[i].push(source); > // Save New Key else < map[i] = source; >> > return map; > window.location.query.makeString = function (source, addQuestionMark) < var str = "", i, ii, key; if (typeof source == "boolean") < addQuestionMark = source; source = undefined; >if (source == undefined) < str = window.location.search; >else < for (i in source) < key = "&" + encodeURIComponent(i); if (Object.prototype.toString.call(source[i]) !== "[object Array]") < str += key + addUndefindedValue(source[i]); >else < for (ii = 0; ii < source[i].length; ii++) < str += key + addUndefindedValue(source[i][ii]); >> > > return (addQuestionMark === false ? "" : "?") + str.substr(1); > function addUndefindedValue(source) < return typeof source === "undefined" ? "" : " mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Sep 22, 2017 at 1:40
answered Nov 19, 2012 at 14:33
Add a comment|
6

You can simply use URLSearchParams().

Lets see we have a page with url:

  • https://example.com/?product=1&category=game

On that page, you can get the query string using window.location.search and then extract them with URLSearchParams() class.

const params = new URLSearchParams(window.location.search) console.log(params.get('product') // 1 console.log(params.get('category') // game

Another example using a dynamic url (not from window.location ), you can extract the url using URL object.

const url = new URL('https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest') console.log(url.search) // ?v=6xJ27BtlM0c&ab_channel=FliteTest 

This is a simple working snippet:

const urlInput = document.querySelector('input[type=url]') const keyInput = document.querySelector('input[name=key]') const button = document.querySelector('button') const outputDiv = document.querySelector('#output') button.addEventListener('click', () => < const url = new URL(urlInput.value) const params = new URLSearchParams(url.search) output.innerHTML = params.get(keyInput.value) >)
 


Источник

Get Query String Values in JavaScript

In a URL, query string values often provide information about the request, like parameters for a search or the ID of an object you're using. If any of the business or request logic is handled in the frontend, it's important to know how to retrieve the query string values from the URL. There are a number of ways to achieve this, a few of which we'll see here.

URLSearchParams

The URLSearchParams interface is supported by all major browser versions except IE 11. It works by parsing the query string of a URL and providing a way to access the values. For example:

let params = new URLSearchParams('q=node&page=2'); params.get('q'); // 'node' params.get('page'); // '2' 

One of the downsides of this interface is that you must pass it only the query string of a URL. If you're working with the current browser URL, that's easy to do since you can just pass window.location.search . If you're working with any other URL, you'll need to parse out and pass the query string separately.

To parse the query parameters into an object, use URL.searchParams 's .entries() method, which returns an Iterator of key/value pairs, and Object.fromEntries to convert it into an object.

let params = new URLSearchParams('q=node&page=2'); let entries = params.entries(); Object.fromEntries(entries); // 

URL Object

The URL API is also supported by all major browser versions except IE 11. It offers a more flexible way to parse URLs, and it also provides a way to access the query string values. For example:

const url = new URL('https://stackabuse.com/search?q=node&page=2'); const searchParams = url.searchParams; searchParams.get('q'); // 'node' searchParams.get('page'); // '2' 

url.searchParams is the same type of instance object returned by URLSearchParams .

The url object above also has all parts of the URL broken out into its parts. For example:

url.href; // 'https://stackabuse.com/search?q=node&page=2' url.origin; // 'https://stackabuse.com' url.protocol; // 'https:' url.host; // 'stackabuse.com' url.hostname; // 'stackabuse.com' url.port; // '' url.pathname; // '/search' url.search; // '?q=node&page=2' url.hash; // '' 

Pure JavaScript

If for any reason you're not able to access the APIs above or want to have more control over the parsing, you can use the following code to parse the query string into an object.

function getQueryParams(url) < const paramArr = url.slice(url.indexOf('?') + 1).split('&'); const params = <>; paramArr.map(param => < const Javascript get query param = param.split('='); paramsJavascript get query param = decodeURIComponent(val); >) return params; > 

Note: There are many ways to parse query params in plain JS, some more complicated (and robust) than others. This is just one way, and was adapted from this gist.

We can then use this plain JS function to parse a single query param into a string:

getQueryParams('https://stackabuse.com/search?q=node&page=2') // 

Источник

How to get "GET" request parameters in JavaScript? [duplicate]

How to get "GET" variables from request in JavaScript? Does jQuery or YUI! have this feature built-in?

12 Answers 12

Update June 2021:

Today's browsers have built-in APIs for working with URLs (URL) and query strings (URLSearchParams) and these should be preferred, unless you need to support some old browsers or Opera mini (Browser support).

All data is available under

you have to parse the string, eg.

just call the function with GET variable name as parameter, eg.

this function will return the variables value or undefined if variable has no value or doesn't exist

@Daniel Silveira: yes, it could/should decode the value (and encode the name). Will edit my post in few moments

Note that decodeURIComponent does not decode /all/ possible URI escapes. In particular "+" won't be decoded as " ". (I forget which browser this was in. FF, maybe?) The spec requires them to only decode exactly what encodeUIRComponent encodes, and it will encode " " as "%20", so "+" is left alone.

@volocuga unlike PHP, dealing with URLs in JavaScript is quite rare operation, so browser vendors never really focused on these features.

You could use jquery.url I did like this:

var xyz = jQuery.url.param("param_in_url"); 

@Adam it would appear so. I think this is the updated URL: github.com/allmarkedup/jQuery-URL-Parser A google search on Mark Perkins jquery.url led me to an update. I have the source from when I posted this answer if you need it.

var xyz = jQuery.url().param("param_in_url"); is the correct syntax where jQuery.url() gives the the current page URL. Please make the correction.

try the below code, it will help you get the GET parameters from url . for more details.

 var url_string = window.location.href; // www.test.com?filename=test var url = new URL(url_string); var paramValue = url.searchParams.get("filename"); alert(paramValue) 

not works in example localhost:8080/#/?access_token=111 because of location.hash part. If '#' symbol occurs location.search is empty

url with "#" symbol is not supported so we have to remove that. try this : var url_string = window.location.href; // www.test.com?filename=test var url = new URL(url_string.replace("#/","")); var paramValue = url.searchParams.get("access_token"); alert(paramValue)

Just to put my two cents in, if you wanted an object containing all the requests

function getRequests() < var s1 = location.search.substring(1, location.search.length).split('&'), r = <>, s2, i; for (i = 0; i < s1.length; i += 1) < s2 = s1[i].split('='); r[decodeURIComponent(s2[0]).toLowerCase()] = decodeURIComponent(s2[1]); >return r; >; var QueryString = getRequests(); //if url === "index.html?test1=t1&test2=t2&test3=t3" console.log(QueryString["test1"]); //logs t1 console.log(QueryString["test2"]); //logs t2 console.log(QueryString["test3"]); //logs t3 

Note, the key for each get param is set to lower case. So, I made a helper function. So now it's case-insensitive.

Unlike other answers, the UrlSearchParams object can avoid using Regexes or other string manipulation and is available is most modern browsers:

var queryString = location.search let params = new URLSearchParams(queryString) // example of retrieving 'id' parameter let

You can use the URL to acquire the GET variables. In particular, window.location.search gives everything after (and including) the '?'. You can read more about window.location here.

var urlParams = location.search.split(/[?&]/).slice(1).map(function(paramPair) < return paramPair.split(/=(.+)?/).slice(0, 2); >).reduce(function (obj, pairArray) < obj[pairArray[0]] = pairArray[1]; return obj; >, <>); 
For url: http://example.com?one=1&two=2 console.log(urlParams.one) // 1 console.log(urlParams.two) // 2 

Could you please address why would you use a map-reduce solution for this? As far as I understand, map-reduce is efficient when handling really big datasets. As this is just an HTTP request, I don't see the point of using a map-reduce solution.

actually map/reduce is just a collections processing mechanism: can be used with any size data. it is more famous for big data due to its willingness to be parallelized

Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an = as true .

// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else var _GET = (function() < var _get = <>; var re = /[?&]([^=&]+)(=?)([^&]*)/g; while (m = re.exec(location.search)) _get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true); return _get; >)(); console.log(_GET); > Object console.log(_GET['something else']); > true console.log(_GET.abc); > 123 

Источник

Читайте также:  Check marks in html
Оцените статью