JavaScript Get URL Parameters

Here’s a great article from The Crazy Programmer

In this tutorial, I will tell you about how you can get URL parameters with javascript.

Passing URL parameters is a nice way to move from one page to another. As we know URL is string in which there are certain variables present which are used to move forward to the new page. You can get it by checking in URL string the text written after question mark shows the variable name, value pair follow separated by an ampersand.

The disadvantage of using this method is that it is visible to the user and anyone can manipulate it by manual editing. There are some other secure ways that we can do this is by using post method, session cookies, or database to store the variables.

Basically, for this, we have to understand how it is passed.

There are various ways buy which we can fetch the parameters from url, lets have a look on them one by one.

JavaScript Get URL Parameters

Method 1:

First way is by using searchParams javascript method. This method is used to get value of particular variable.

var link = "";
var  extractParameter= new URL(link);
var  final = extractParameter.searchParams.get("link");

You can get the current link by using window.location.href, just replace link variable string with this method.

Method 2:

Another way is by using split method.

var urlLink = '';
var query_paramter = urlLink.split("?")[1];  

Method 3:

The third way is by using the regular expression.

function getUrlVars( name, link ) {
    if (!link) link = location.href;
    name = name.replace(/[[]/,"[").replace(/[]]/,"]");
    var regexS = "[?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( url );
    return results == null ? 'Empty' : results[1];

console.log(getUrlVars('text', ''));

In this method, I also handled that if at some instance parameter is missing then it returns undefined which is a bad coding practice. So to correct this we first check that particular parameter is present or not. If not present then send some default value.

So there are some characters that can not pass through URL like suppose we write a space in the link and press enter key then space will be replaced by %20code. So it is also important to encode and decode the URL parameters. There are the following functions you can use to do this. In these functions, you have to pass URL string.

To decode use decodeURI(urlValue) and to encode use encodeURI(urlValue).

Comment down below if you know any other way to fetch url parameters in javascript.

The post JavaScript Get URL Parameters appeared first on The Crazy Programmer.

Source link