Reading URL variables in Javascript

Date Posted: September 2, 2014, 7:12 am


For example you want to get the value of ‘firstname’ on this URL: http://carlofontanos.com/?firstname=carlo&lastname=fontanos

In PHP, we can simply access the value by using the $_GET[], since Javascript does not have any built-in function like this, we need to create our own.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script type="text/javascript">
jQuery(document).ready(function($){
   
    function cvf_get_url_value(variable) {
           var query = window.location.search.substring(1);
           var vars = query.split("&");
           for (var i=0;i<vars.length;i++) {
                   var pair = vars[i].split("=");
                   if(pair[0] == variable){return pair[1];}
           }
           return(false);
    }
});
</script>

Get the value of ‘firstname’:

1
cvf_get_url_value('firstname');

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me