getUrlParams.js

About

This tool converts URL (get) params to given format.

Guide

Calling without arguments

Calling without parsers returns get params in string format

// getUrlParams(parsers)

const { title, num } = getUrlParams();

// ?title=Text&num=5
// title === 'Text', num === '5'

Parsers argument

You can convert params to given format by adding parsers argument

const params = getUrlParams({
  num: Number,
  isTrue: Boolean,
  dayOfWeek: (param) =>
    (['Sun','Mon','Tue','Wed','Thu','Fri','Sat'])[Number(param)]
});

// ?title=Text&num=5&isTrue=1&dayOfWeek=2
// params === { title: 'Text', num: 5, isTrue: true, dayOfWeek: 'Tue' }

Missing params

Missing params are undefined even if parser is specified

const params = getUrlParams({
 a: Boolean,
 b: Boolean,
 c: Boolean
});

// ?a=1&c=1
// params === { a: true, c: true }

Multiple params

If there will be multiple params with the same name, only the last one will be in result

const { letter } = getUrlParams();

// ?letter=a&letter=b&letter=c
// letter === 'c'

Sources

The sources can be found on Github:

JavaScript sources

And if you love TypeScript as I am, here is the link for you:

TypeScript sources