Created
September 21, 2021 13:38
-
-
Save IvanAdmaers/12e93a24b244798ef7d4e4c7df137aeb to your computer and use it in GitHub Desktop.
AddParamsToUrl | NodeJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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