Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve GET parameters from JavaScript [duplicate]

Tags:

javascript

get

Consider:

http://example.com/page.html?returnurl=%2Fadmin 

For js within page.html, how can it retrieve GET parameters?

For the above simple example, func('returnurl') should be /admin.

But it should also work for complex query strings...

like image 664
compile-fan Avatar asked Mar 27 '11 10:03

compile-fan


People also ask

How do I find URL parameters?

Method 1: Using the URLSearchParams Object The URLSearchParams is an interface used to provide methods that can be used to work with an URL. The URL string is first separated to get only the parameters portion of the URL. The split() method is used on the given URL with the “?” separator.

How do I pass multiple parameters in URL?

Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".


1 Answers

With the window.location object. This code gives you GET without the question mark.

window.location.search.substr(1) 

From your example it will return returnurl=%2Fadmin

EDIT: I took the liberty of changing Qwerty's answer, which is really good, and as he pointed I followed exactly what the OP asked:

function findGetParameter(parameterName) {     var result = null,         tmp = [];     location.search         .substr(1)         .split("&")         .forEach(function (item) {           tmp = item.split("=");           if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);         });     return result; } 

I removed the duplicated function execution from his code, replacing it a variable ( tmp ) and also I've added decodeURIComponent, exactly as OP asked. I'm not sure if this may or may not be a security issue.

Or otherwise with plain for loop, which will work even in IE8:

function findGetParameter(parameterName) {     var result = null,         tmp = [];     var items = location.search.substr(1).split("&");     for (var index = 0; index < items.length; index++) {         tmp = items[index].split("=");         if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);     }     return result; } 
like image 86
Bakudan Avatar answered Oct 22 '22 04:10

Bakudan