Skip to content

Instantly share code, notes, and snippets.

@tripulse
Last active March 8, 2019 10:21
Show Gist options
  • Save tripulse/09217ae0e7abe7a5242fa1b032f8be7b to your computer and use it in GitHub Desktop.
Save tripulse/09217ae0e7abe7a5242fa1b032f8be7b to your computer and use it in GitHub Desktop.
Parses QueryString and returns URL agruments.
function GetQueryString( qs ) {
if ( !qs ) return;
var QueryStrings = [];
var SearchParams = new URLSearchParams( qs );
for ( Query of SearchParams ) {
QueryStrings.push( Query );
}
function EntriesToObject( Entries ) {
if ( Array.isArray( Entries ) ) {
var EntriesObject = {};
Entries.forEach( entry => {
EntriesObject[ entry[ 0 ] ] = entry[ 1 ];
} );
return EntriesObject;
}
}
QueryStrings = EntriesToObject( QueryStrings );
}
@tripulse
Copy link
Author

tripulse commented Aug 24, 2018

Usage

Takes qs argument as QueryString. Otherwise returns nothing.

var QueryString = ParseQueryString(location.search); /** URL QueryString **/
console.log(QueryString) /** TypeOf Object **/

Note: This API is new mayn't be supported in older Web browsers. Use pollyfill.

@tripulse
Copy link
Author

tripulse commented Mar 8, 2019

This also could be done using:

var searchParams = 
new URL(location.href)
.searchParams;

// This is how you do it!
var params = 
Array.from(searchParams.entries())
.reduce((accum, [k, v]) => {
  accum[k] = v;
  return accum;
}, {});

Thanks to this StackOverflow answer.

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