63

I'm trying to pass data from one page to another.

www.mints.com?name=something

How to read name using JavaScript?

12 Answers 12

69

Please see this, more current solution before using a custom parsing function like below, or a 3rd party library.

The a code below works and is still useful in situations where URLSearchParams is not available, but it was written in a time when there was no native solution available in JavaScript. In modern browsers or Node.js, prefer to use the built-in functionality.


function parseURLParams(url) {
    var queryStart = url.indexOf("?") + 1,
        queryEnd   = url.indexOf("#") + 1 || url.length + 1,
        query = url.slice(queryStart, queryEnd - 1),
        pairs = query.replace(/\+/g, " ").split("&"),
        parms = {}, i, n, v, nv;

    if (query === url || query === "") return;

    for (i = 0; i < pairs.length; i++) {
        nv = pairs[i].split("=", 2);
        n = decodeURIComponent(nv[0]);
        v = decodeURIComponent(nv[1]);

        if (!parms.hasOwnProperty(n)) parms[n] = [];
        parms[n].push(nv.length === 2 ? v : null);
    }
    return parms;
}

Use as follows:

var urlString = "http://www.example.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";
    urlParams = parseURLParams(urlString);

which returns a an object like this:

{
  "a"  : ["a a"],     /* param values are always returned as arrays */
  "b b": ["b"],       /* param names can have special chars as well */
  "c"  : ["1", "2"]   /* an URL param can occur multiple times!     */
  "d"  : [null]       /* parameters without values are set to null  */ 
} 

So

parseURLParams("www.mints.com?name=something")

gives

{name: ["something"]}

EDIT: The original version of this answer used a regex-based approach to URL-parsing. It used a shorter function, but the approach was flawed and I replaced it with a proper parser.

8
  • @Tomalak can you please tell me the way to print the value of name? i am trying to use this script and when i use document.write(urlParams); it gives me [object Object] but i dont get the actual value.. Can you help me with this please? Jun 27, 2013 at 21:33
  • @KiranVemuri: Try console.log(JSON.stringify(urlParams)) Sep 26, 2014 at 7:13
  • How to only get the key and not the value? For example - if url is like example.php?name, in this case it doesn't contain name=something, I only want to get name because my url is dynamic so that value can change so I need a way to get that value.
    – gegobyte
    Aug 12, 2016 at 17:35
  • 1
    Well getting only the key is actually very easy, I did - for(var a in parms) { console.log(a); } This only returned the key.
    – gegobyte
    Aug 13, 2016 at 5:22
  • 2
    If anyone was still wondering how to get the data from urlParams the syntax is: urlParams["name"][0] which would return: "something" Mar 6, 2017 at 15:25
47

It’s 2019 and there is no need for any hand-written solution or third-party library. If you want to parse the URL of current page in browser:

# running on https://www.example.com?name=n1&name=n2
let params = new URLSearchParams(location.search);
params.get('name') # => "n1"
params.getAll('name') # => ["n1", "n2"]

If you want to parse a random URL, either in browser or in Node.js:

let url = 'https://www.example.com?name=n1&name=n2';
let params = (new URL(url)).searchParams;
params.get('name') # => "n1"
params.getAll('name') # => ["n1", "n2"]

It’s making use of the URLSearchParams interface that comes with modern browsers.

5
  • What is that location.search ? I am getting an error there.
    – ShashankAC
    May 25, 2020 at 13:56
  • @ShashankAC Which browser are you using? May 26, 2020 at 6:01
  • I am using Google Chrome
    – ShashankAC
    May 26, 2020 at 7:05
  • @ShashankAC That’s really weird. It works on my Chrome. On which page are you testing this? For example, does location.search gives you anything on example.com/?foo=bar? May 28, 2020 at 6:54
  • Oh sorry, I am using react so I should put this.props.location.search
    – ShashankAC
    May 29, 2020 at 2:04
9

try this way

var url_string = window.location;
var url = new URL(url_string);
var name = url.searchParams.get("name");
var tvid = url.searchParams.get("id");
1
  • 1
    Simplest answer
    – Dshiz
    Aug 26, 2020 at 1:18
9

You can easily do this

const shopId =  new URLSearchParams(window.location.search).get('shop_id');
console.log(shopId);
7

I think this should also work:

function $_GET(q,s) {
    s = (s) ? s : window.location.search;
    var re = new RegExp('&amp;'+q+'=([^&amp;]*)','i');
    return (s=s.replace(/^\?/,'&amp;').match(re)) ?s=s[1] :s='';
}

Just call it like this:

var value = $_GET('myvariable');
0
4

Here's one solution. Of course, this function doesn't need to load into a "window.params" option -- that can be customized.

window.params = function(){
    var params = {};
    var param_array = window.location.href.split('?')[1].split('&');
    for(var i in param_array){
        x = param_array[i].split('=');
        params[x[0]] = x[1];
    }
    return params;
}();

Example API call on http://www.mints.com/myurl.html?name=something&goal=true:

if(window.params.name == 'something') doStuff();
else if( window.params.goal == 'true') shoutGOOOOOAAALLL();
3

location.search https://developer.mozilla.org/en/DOM/window.location

although most use some kind of parsing routine to read query string parameters.

here's one http://safalra.com/web-design/javascript/parsing-query-strings/

3

I also made a fairly simple function. You call on it by: get("yourgetname");

and get whatever there was. (now that i wrote it i noticed it will give you %26 if you had a & in your value..)

function get(name){
  var url = window.location.search;
  var num = url.search(name);
  var namel = name.length;
  var frontlength = namel+num+1; //length of everything before the value 
  var front = url.substring(0, frontlength);  
  url = url.replace(front, "");  
  num = url.search("&");

 if(num>=0) return url.substr(0,num); 
 if(num<0)  return url;             
}
2

The currently selected answer did not work well at all in my case, which I feel is a fairly typical one. I found the below function here and it works great!

function getAllUrlParams(url) {

  // get query string from url (optional) or window
  var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

  // we'll store the parameters here
  var obj = {};

  // if query string exists
  if (queryString) {

    // stuff after # is not part of query string, so get rid of it
    queryString = queryString.split('#')[0];

    // split our query string into its component parts
    var arr = queryString.split('&');

    for (var i=0; i<arr.length; i++) {
      // separate the keys and the values
      var a = arr[i].split('=');

      // in case params look like: list[]=thing1&list[]=thing2
      var paramNum = undefined;
      var paramName = a[0].replace(/\[\d*\]/, function(v) {
        paramNum = v.slice(1,-1);
        return '';
      });

      // set parameter value (use 'true' if empty)
      var paramValue = typeof(a[1])==='undefined' ? true : a[1];

      // (optional) keep case consistent
      paramName = paramName.toLowerCase();
      paramValue = paramValue.toLowerCase();

      // if parameter name already exists
      if (obj[paramName]) {
        // convert value to array (if still string)
        if (typeof obj[paramName] === 'string') {
          obj[paramName] = [obj[paramName]];
        }
        // if no array index number specified...
        if (typeof paramNum === 'undefined') {
          // put the value on the end of the array
          obj[paramName].push(paramValue);
        }
        // if array index number specified...
        else {
          // put the value at that index number
          obj[paramName][paramNum] = paramValue;
        }
      }
      // if param name doesn't exist yet, set it
      else {
        obj[paramName] = paramValue;
      }
    }
  }

  return obj;
}
1
  • Hi! Thanks for that function. Can you give the same function, but in TypeScript? Jan 11, 2021 at 15:51
1

Iv'e fixed/improved Tomalak's answer with:

  • Make an Array only if needed.
  • If there's another equation symbol in the value it gets inside the value
  • It now uses the location.search value instead of a url.
  • Empty search string results in an empty object.

Code:

function getSearchObject() {
    if (location.search === "") return {};

    var o = {},
        nvPairs = location.search.substr(1).replace(/\+/g, " ").split("&");

    nvPairs.forEach( function (pair) {
        var e = pair.indexOf('=');
        var n = decodeURIComponent(e < 0 ? pair : pair.substr(0,e)),
            v = (e < 0 || e + 1 == pair.length) 
                ? null : 
                decodeURIComponent(pair.substr(e + 1,pair.length - e));
        if (!(n in o))
            o[n] = v;
        else if (o[n] instanceof Array)
            o[n].push(v);
        else
            o[n] = [o[n] , v];
    });
    return o;
}
0

Try like this.. Eg : www.example.com?id=1

$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.search);
    return (results !== null) ? results[1] || 0 : false;
}
console.log($.urlParam('id'));

Hope it helps. :)

0

You can do like this

function parseURLParams(url) {
        var queryStart = url.indexOf("?") + 1,
            queryEnd   = url.indexOf("#") + 1 || url.length + 1,
            query = url.slice(queryStart, queryEnd - 1),
            pairs = query.replace(/\+/g, " ").split("&"),
            parms = {}, i, n, v, nv;

        if (query === url || query === "") return;

        for (i = 0; i < pairs.length; i++) {
            nv = pairs[i].split("=", 2);
            n = decodeURIComponent(nv[0]);
            v = decodeURIComponent(nv[1]);

            if (!parms.hasOwnProperty(n)) parms[n] = [];
            parms[n].push(nv.length === 2 ? v : null);
        }
        return parms;
    }

    //enter code here


    var urlString = "http://www.examle.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";

    urlParams = parseURLParams(urlString);
    console.log(urlParams)

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.