You may familiar to retrieve query string parameters in any server side language like php.
Let the url is
coderexample.html?post_id=239&category=Angular
if you want to get 239 from above url you can easily write $_GET[‘post_id’] or something like $_REQUEST[‘post_id’].
You can also get category Angular using $_GET[‘category’]/$_REQUEST[‘category’].
In this tutorial, I will show how to fetch query string parameters ie, id & category from above url using javascript.
Step1: Get current url
1 | window.location.href; // coderexample.html?post_id=239&category=Angular |
Step2: get “?” position and slice the remaining part from the url
1 | window.location.href.slice(window.location.href.indexOf('?') + 1) // post_id=239&category=Angular |
Step3: convert to an array
1 2 | var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); // ["id=239", "category=Angular"] |
Step4: Push in a new array according to index and value by slicing “=”
1 2 3 4 5 6 7 | var params; for (var i=0;i<url.length;i++) { params = url[i].split("="); } console.log(params[0]); //239 console.log(params[1]); //Angular |
So we have extracted the parameters. Let’s create a generalized function, so we can fetch value by index.
1 2 3 4 5 6 7 8 9 | function getParam(param) { var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i=0;i<url.length;i++) { var params = url[i].split("="); if(params[0] == param) return params[1]; } return false; } |
Now you can get value simply calling getParam() function by index.
1 2 | getParam("id") // 239 getParam("category") // 239 |
0 Comments