Let's say I have a page called https://randompagename.com, I know I can send GET parameters to this page using this syntax: https://randompagename.com/?parameter1="one"¶meter2="two".
I also know that on a Node.js web app I have an easy way of getting these parameters inside a variable. However, when I'm using pure frontend Javascript without Node.js, I usually solve this problem with something like:
const myURL = decodeURI(window.location.href)
This way, I discover that my page is https://randompagename.com/?parameter1="one"¶meter2="two" and then I can parse it excluding everything after the first =
sign and then splitting everything on &
. Well, even though this is functional I'm probably missing an easier way of solving this problem. How can I get GET parameters on a page without using any library?
CodePudding user response:
You can use the URL object https://developer.mozilla.org/en-US/docs/Web/API/URL
If the URL of your page is https://example.com/?name=Jonathan Smith&age=18 you could parse out the name and age parameters using:
let searchString = (new URL(document.location)).search; //?name=Jonathan Smith&age=18
let params = (new URL(document.location)).searchParams;
let name = params.get('name'); // is the string "Jonathan Smith".
let age = parseInt(params.get('age')); // is the number 18