Skip to content

Instantly share code, notes, and snippets.

@laurendorman
Created February 14, 2019 17:45
Show Gist options
  • Select an option

  • Save laurendorman/f88d753515e57d6d5df0d40c5372d011 to your computer and use it in GitHub Desktop.

Select an option

Save laurendorman/f88d753515e57d6d5df0d40c5372d011 to your computer and use it in GitHub Desktop.

Revisions

  1. laurendorman created this gist Feb 14, 2019.
    52 changes: 52 additions & 0 deletions updateQuery.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    export default function updateQuery(params) {
    window.location.search = encodeURIParams(mergeObjects(decodeURIParams(), params), true);
    };

    function decodeURIParams(query) {
    if (query == null) {
    query = window.location.search;
    }

    if (query[0] == '?') {
    query = query.substring(1);
    }

    var params = query.split('&');
    var result = {};
    for (let i = 0; i < params.length; i++) {
    const param = params[i];
    const pos = param.indexOf('=');
    if (pos >= 0) {
    const key = decodeURIComponent(param.substring(0, pos));
    const val = decodeURIComponent(param.substring(pos + 1));
    result[key] = val;
    } else {
    const key = decodeURIComponent(param);
    }
    }

    return result;
    }

    function encodeURIParams(params, addQuestionMark) {
    const pairs = [];
    for (const key in params) if (params.hasOwnProperty(key)) {
    const value = params[key];
    if (value != null) /* matches null and undefined */ {
    pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
    }
    }
    if (pairs.length == 0) {
    return '';
    }

    return (addQuestionMark ? '?' : '') + pairs.join('&');
    }

    function mergeObjects(destination, source) {
    for (var key in source) if (source.hasOwnProperty(key)) {
    destination[key] = source[key];
    }

    return destination;
    }