3

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?

Arnav Thorat
  • 3,078
  • 3
  • 8
  • 33
test1
  • 95
  • 1
  • 7

3 Answers3

7

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);
Bravo
  • 6,022
  • 1
  • 10
  • 15
2

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

shotgun02
  • 756
  • 4
  • 14
0

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sid
  • 4,893
  • 14
  • 55
  • 110