Skip to content

Instantly share code, notes, and snippets.

@gx0r
Last active March 26, 2019 20:51
Show Gist options
  • Save gx0r/3af6e19ecf1c0fd1ad41959cb9fa1aa0 to your computer and use it in GitHub Desktop.
Save gx0r/3af6e19ecf1c0fd1ad41959cb9fa1aa0 to your computer and use it in GitHub Desktop.
One line QueryString parser - handles repeated parameters, initial question-mark is optional, handles null parameters, handles + in parameters, and decodes URI Components.
'use strict';
/**
"One line" QueryString parser
Initial question-mark optional
Handles repeated parameters (turns into array)
Handles null parameters
Handles + sign in parameters
Decodes URI Components
If no string is passed, uses "window.location.search", if it exists
Creates a bare object (Object.create(null)) so Object properties aren't present.
*/
const assert = require('assert');
// the function
function queryStringToObject(query) {
if (!(typeof query === 'string')) {
if (typeof window === 'object' && typeof window.location === 'object' && typeof window.location.search === 'string') {
return queryStringToObject(window.location.search);
} else {
return Object.create(null);
}
}
return query.substring(query[0] == '?' ? 1 : 0)
.split('&')
.reduce(function (acc, cur) {
var split = cur.split('=').map(function (val) {
return decodeURIComponent(val.replace(/\+/g, ' '));
});
Array.isArray(acc[split[0]]) ? acc[split[0]].push(split[1]) : acc[split[0]] == null ? acc[split[0]] = split[1] : acc[split[0]] = [acc[split[0]], split[1]];
return acc;
}, Object.create(null));
}
// the tests
var query = "?id=33&id=55&asdf=%26lols%3F&null=&null2=&3=blah+blah" ;
var qs = queryStringToObject(query);
assert.deepEqual(qs,
{
'3': 'blah blah',
id: ['33', '55'],
asdf: '&lols?',
null: '',
null2: ''
}
);
assert.deepEqual(Object.create(null), queryStringToObject() );
assert.deepEqual(queryStringToObject("id=3ƒƒ•£®∆3&id=55&asdf=%26lols%3F&null=&null2=&3=blah+blah"),
{
'3': 'blah blah',
id: ['3ƒƒ•£®∆3', '55'],
asdf: '&lols?',
null: '',
null2: ''
}
);
console.log(qs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment