Created
December 13, 2017 12:24
-
-
Save davidhund/36ddef4b9c54790633b60044150e7d98 to your computer and use it in GitHub Desktop.
Get URL parameters from String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get URL parameters from String | |
* source: https://css-tricks.com/snippets/javascript/get-url-variables/ | |
* @param {String} url The URL | |
* @return {Object} The URL parameters | |
*/ | |
var getParams = function (url) { | |
var params = {}; | |
var parser = document.createElement('a'); | |
parser.href = url; | |
var query = parser.search.substring(1); | |
if (query) { | |
var vars = query.split('&'); | |
for (var i = 0; i < vars.length; i++) { | |
var pair = vars[i].split('='); | |
params[pair[0]] = decodeURIComponent(pair[1]); | |
} | |
} | |
return params; | |
}; | |
// Usage: | |
// getParams(window.location.href); // from window URL | |
// getParams('http://some.url?page=1&id=2'); // from String |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The above is a bit oldskool.
A new ES6 way would be e.g.:
There is a better (native way) with
URLSearchParams
:See: https://developers.google.com/web/updates/2016/01/urlsearchparams?hl=en
but (IE) support is lacking... (Polyfilled)