Javascript Solution: How to get URL parameter’s value in javascript?

Overview

In this post, will explain a problem which we often struggle with. How do we get query parameter values from a URL in Javascript?

There isn’t a simple straight forward request object which could help you. However, There are many ways (custom solutions) which you could try. Here is one of the custom solution to get the value of the parameter

Sample Code

// To get array of parameters
function getAllParameters(url) {
        var params = {};
        var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi,  function(m,key,value) {
            params[key] = value;
        });
        return params;
    };
//Get the value of the parameter
  function getParamValue(param, url){
        var paramValue = '';
        if(url.indexOf(param) > -1){
            paramValue = getAllParameters(url)[param];
        }
        return paramValue;
 }
#INPUT
var sampleURL = 'https://www.example.com?productCode=938939&productName=fcybers';
console.log(getParamValue('productCode' , sampleURL))
console.log(getParamValue('productName' , sampleURL))
#OUTPUT
938939
fcybers

Advertisements


Categories: Javascript solutions

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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