0

Check this image I have this link in (note this link not from search URL) var link = https://google.com/?ib=10 in main.js file. Now how to get that 10 from this link in javaScript on Page load

I have tried this way

var link1 = link;
const url3 = new URLSearchParams(link1);
    const ur = url3.get("ib");
    var finaltgid = ur;
    alert(ur);

But its not working may be this code only work when we use window.location.search Instead of var or const

  • Hey, this question is answered here with more details. https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript https://stackoverflow.com/questions/979975/get-the-values-from-the-get-parameters-javascript – Xab Ion Feb 12 '22 at 03:46
  • Does this answer your question? [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – esqew Feb 12 '22 at 03:56
  • Sir, I want to get from var not from Search url – Ft. Debjit Feb 12 '22 at 03:58

3 Answers3

0

urlsearchparams does not parse full url, you need to pass only query part, like this:

var link = 'https://google.com/?ib=10';
const url = new URLSearchParams(new URL(link).search);
const ib = url.get("ib");
console.log(ib);
Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
0

URLSearchParams only accepts the actual query part in the constructor. You are including the full link.

RyloRiz
  • 77
  • 2
0

Edit: For a given link you can just supply the link in place of document.location (which directly fetches the pages current location)

Considering this as Vanilla JS. You can do the following.

let params = (new URL(document.location)).searchParams;

let ib = parseInt(params.get('ib')); // is the number 10

Note, using the parseInt to get the value as a number.

innocent
  • 864
  • 6
  • 17