UNPKG

875 BJavaScriptView Raw
1/**
2 * Utility module to work with urls.
3 *
4 * @module url
5 */
6
7import * as object from './object.js'
8
9/**
10 * Parse query parameters from an url.
11 *
12 * @param {string} url
13 * @return {Object<string,string>}
14 */
15export const decodeQueryParams = url => {
16 /**
17 * @type {Object<string,string>}
18 */
19 const query = {}
20 const urlQuerySplit = url.split('?')
21 const pairs = urlQuerySplit[urlQuerySplit.length - 1].split('&')
22 for (var i = 0; i < pairs.length; i++) {
23 const item = pairs[i]
24 if (item.length > 0) {
25 const pair = item.split('=')
26 query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '')
27 }
28 }
29 return query
30}
31
32/**
33 * @param {Object<string,string>} params
34 * @return {string}
35 */
36export const encodeQueryParams = params =>
37 object.map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&')