'Get url parameter with javascript

I try to get a URL parameter nr, but I get always false.

var url = window.location.href;
let params = new URLSearchParams(url.search);
let nr = params.has('nr')

What is the error?



Solution 1:[1]

Use

var url = window.location;
let params = new URLSearchParams(url.search);
let nr = params.has('nr')

because window.location is a Location object with a .search property

whereas window.location.href is a string, without a .search property

therefore your url.search is undefined

I can demonstrate with URL which is similar to Location in this respect

let loc = new URL('http://example.com/?nr=1');

// loc is a placeholder for your window.location

let url = loc.href;

// here, url.search would be window.location.href.search
let params = new URLSearchParams(url.search);
let nr = params.has('nr')
console.log(nr);

url = loc;

// here, url.search would be window.location.search
params = new URLSearchParams(url.search);
nr = params.has('nr')
console.log(nr);

Solution 2:[2]

From https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

The URLSearchParams constructor does not parse full URLs. However, it will strip an initial leading ? off of a string, if present.

So you should only provide the query params string.

e.g. if your window.location.href is

https://stackoverflow.com/questions/68314446/get-url-parameter-with-javascript?query=1&query_1=2&many_queries=3

Then you should pass the URLSearchParams class only the query params, viz query=1&query_1=2&many_queries=3

Solution 3:[3]

The below function will return Array of all parameters from url

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,    
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }
  
  var params = getUrlVars();
  
  console.log(params["nr"]);

reference taken from https://stackoverflow.com/a/20097994/8077687

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dharman
Solution 3 shotgun02