UNPKG

@ithaka/bonsai

Version:
86 lines (69 loc) 2.08 kB
"use strict"; const _removeHash = (url) => { if(url) { return url.split("#")[0]; } }, _getHash = (url) => { let parts = url.split("#"); return parts.length === 2 ? "#" + parts[1] : ""; }, _removeQuery = (url) => { if(url) { return url.split("?")[0]; } }, _getQuery = (url) => { let parts = url.split("?"); return parts.length === 2 ? _removeHash(parts[1]) : ""; }; export function updateUrlParameter(origUrl, key, value) { if (!origUrl || !key || !value){ throw new Error("Incorrect number of parameters passed, need 'url', 'key' and 'value'"); } key = encodeURIComponent(key); value = encodeURIComponent(value); let params, keyExists = false; const currentQueryString = _getQuery(origUrl); if(currentQueryString) { params = currentQueryString.split("&"); params.forEach(function(param, index) { let pair = param.split("="); if(pair[0] === key) { pair[1] = value; params[index] = pair.join("="); keyExists = true; } }); } else { params = []; } if(!keyExists) { params = params.concat([key, value].join("=")); } const baseUrl = _removeQuery(origUrl); const hash = _getHash(origUrl); return `${baseUrl}?${params.join("&")}${hash}`; } export function getUrlParameterValue(origUrl, key) { if (!origUrl || !key){ throw new Error("Incorrect number of parameters passed, need 'url' and 'key'"); } let currentQueryString, params, pair, targetVal = false; currentQueryString = _getQuery(origUrl); if(currentQueryString) { params = currentQueryString.split("&"); $.each(params, function(index, param) { pair = param.split("="); if(pair[0] === key) { targetVal = pair[1]; return false; } }); } return targetVal; }