Skip to content

Instantly share code, notes, and snippets.

@patrickbjohnson
Last active April 1, 2019 22:58
Show Gist options
  • Select an option

  • Save patrickbjohnson/ed7a53c22b3929b242ea008fd4e16c60 to your computer and use it in GitHub Desktop.

Select an option

Save patrickbjohnson/ed7a53c22b3929b242ea008fd4e16c60 to your computer and use it in GitHub Desktop.
params helper
import _ from 'underscore';
/**
*
* @param {string} term
* Checks if the term exists or not. Primary a helper function.
* A term can be a full query parameter or just the name
* EX: 'thank-you' or 'thank-you=true'
*
*/
export const getUrlParam = term => {
return window.location.search.indexOf(term) >= 0;
};
/**
*
* @param {string} name - Query parameter name
* @param {string, boolean, number} value - value to be attached to the name
*
*
* This function does the following:
* 1. Checks if there are existing query parameters.
* If the terms/value being passed in as arguments exists
* they will be overwritten with the new value.
* 2. Converts the query parameters object back to a parameter string
* 3. Replaces the URL with the updated query parameters.
* 4. Appends hash to end of URL if it exists
*
*/
export const setUrlParam = (name, value) => {
let paramString = `${name}=${value}`;
if (window.location.search) {
const hash = location.hash;
const queryParams = _.object(
window.location.href
.replace('#', '')
.split('?')[1]
.split('&')
.map(s => s.split('='))
);
queryParams[name] = value;
paramString = Object.keys(queryParams)
.map(key => key + '=' + queryParams[key])
.join('&');
if (hash) {
paramString = paramString + hash;
}
}
window.history.replaceState(
{},
'',
`${window.location.origin + window.location.pathname}?${paramString}`
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment