tricks
Version:
ES6 modules
29 lines (22 loc) • 682 B
JavaScript
import querystringify from './querystringify.js';
import isEmpty from '../object/isEmpty.js';
export default (url, params, formatFunction) => {
let reg;
if (params) {
// Set default formatting function
formatFunction = formatFunction || encodeURIComponent;
// Override the items in the URL which already exist
for (const x in params) {
const str = `([\\?\\&])${x}=[^\\&]*`;
reg = new RegExp(str);
if (url.match(reg)) {
url = url.replace(reg, `$1${x}=${formatFunction(params[x])}`);
delete params[x];
}
}
}
if (!isEmpty(params)) {
return url + (url.indexOf('?') > -1 ? '&' : '?') + querystringify(params, formatFunction);
}
return url;
};