Skip to content

Instantly share code, notes, and snippets.

@IvanAdmaers
Created September 21, 2021 13:38
Show Gist options
  • Save IvanAdmaers/12e93a24b244798ef7d4e4c7df137aeb to your computer and use it in GitHub Desktop.
Save IvanAdmaers/12e93a24b244798ef7d4e4c7df137aeb to your computer and use it in GitHub Desktop.
AddParamsToUrl | NodeJS
const { URL } = require('url');
/**
* This function adds params to url
*
* @param {stirng} url - Url
* @param {...any} params - Params. E.g. url, param1, param1value, param2, param2value
*/
const addParamsToUrl = (url = '', ...params) => {
const myUrl = new URL(url);
for (let i = 0; i < params.length; i += 2) {
const param = params[i];
const value = params[i + 1];
myUrl.searchParams.append(param, value);
}
return myUrl.toString();
};
module.exports = addParamsToUrl;
const addParamsToUrl = require('./addParamsToUrl');
describe('addParamsToUrl', () => {
it('should be a function', () => {
expect(typeof addParamsToUrl).toBe('function');
});
it('should returns a correct url', () => {
const url = 'https://google.com';
const expectUrl = 'https://google.com/?q=hi';
expect(addParamsToUrl(url, 'q', 'hi')).toBe(expectUrl);
});
it('should returns a correct url', () => {
const url = 'https://google.com/?q=hi';
const expectUrl = 'https://google.com/?q=hi&locale=en-US&year=2021';
expect(addParamsToUrl(url, 'locale', 'en-US', 'year', 2021)).toBe(
expectUrl
);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment