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
CodePudding user response:
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);
CodePudding user response:
URLSearchParams only accepts the actual query part in the constructor. You are including the full link.
CodePudding user response:
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.