Latest Solution to Get URL Parameter Values with Vanilla Javascript ? Query String

0
85
how to get parameter values in javascript query string
?geo=UK&size=300x600

How to get the value from URL Parameters ?

Hey, Welcome to the tutorial. Today, we will learn How to get URL Parameter values ?geo=UK&size=300×600 in Javascript ?

This is the most latest and safe solution you can find in 2019.

How to approach the problem ?

We will solve the problem using URL Object, which is basically getting the url of the page when it loads, then passing it though the URL object, like this

var url = new URL(“https://mrvirk.com?geo=UK&size=300×600”);

Solution Code in Javascript

Follow the code below on Codepen and insert the parameter in codepen url to see results in console.

See the Pen
How to get the value from the GET parameters?
by Navjot Singh Virk (@virksaabnavjot)
on CodePen.

Output

Lets pass the parameters in the URL, ?geo=UK&size=300×600

how to get parameter values in javascript query string
?geo=UK&size=300×600

Code Explanation

We have 2 options –

Statically Pass the URL

var url_string = “https://mrvirk.com?geo=UK&size=300×600”;

OR

Fetch it from the page URL (recommended)

window.onload = function() {
var url_string = (window.location.href).toLowerCase(); }

In this example, I will be using option 2 and getting URL values when the page loads.

  • Firstly, pass the url_string through URL object.
  • Then using the searchParams.get and passing the parameter name like – geo
  • Output Results – The code will return the parameter value for you.
  • Additionally, add try catch for better error handling.

Application of this Tutorial

This article/tutorial is useful if you want to get parameter values, or looking for a solution on how to pass parameter in url in javascript, javascript get url query string, urlsearchparams

Related Articles

Vanilla Javascript solution to return a persons age using their DOB

What’s Javascript ?

Javascript String Explanation, Properties and Methods

SHARE
Previous articleWatch Rabb Da Radio 2
Navjot is a Hobby Blogger from Ireland, and loves to create content to help people. He makes time on weekends to work on this blog. And has a full time position at Yahoo as Technical Solutions Consultant, which he loves and thrives at. His Skills include in-depth knowledge of SEO, Javascript, Advertising, HTML and Java.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.