Skip to content

Instantly share code, notes, and snippets.

@joshbuchea
Last active October 11, 2022 23:13
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joshbuchea/a45c62f8c7bc5697b550 to your computer and use it in GitHub Desktop.
Save joshbuchea/a45c62f8c7bc5697b550 to your computer and use it in GitHub Desktop.
JavaScript - Get URL Query Params
/**
* Returns a bare object of the URL's query parameters.
* You can pass just a query string rather than a complete URL.
* The default URL is the current page.
*/
function getUrlParams (url) {
// http://stackoverflow.com/a/23946023/2407309
if (typeof url == 'undefined') {
url = window.location.search
}
var url = url.split('#')[0] // Discard fragment identifier.
var urlParams = {}
var queryString = url.split('?')[1]
if (!queryString) {
if (url.search('=') !== false) {
queryString = url
}
}
if (queryString) {
var keyValuePairs = queryString.split('&')
for (var i = 0; i < keyValuePairs.length; i++) {
var keyValuePair = keyValuePairs[i].split('=')
var paramName = keyValuePair[0]
var paramValue = keyValuePair[1] || ''
urlParams[paramName] = decodeURIComponent(paramValue.replace(/\+/g, ' '))
}
}
return urlParams
} // getUrlParams
@DanizTom
Copy link

fdsfdsfdsfdsf

@AEROGU
Copy link

AEROGU commented Oct 11, 2022

Here's another one, the computational effort is less because it doesn't use regular expressions:

function getUrlParameter (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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment