Skip to content

Instantly share code, notes, and snippets.

@alexmon
Last active October 13, 2018 12:19
Show Gist options
  • Select an option

  • Save alexmon/574623b0ea6b23e31287d1138fb44b31 to your computer and use it in GitHub Desktop.

Select an option

Save alexmon/574623b0ea6b23e31287d1138fb44b31 to your computer and use it in GitHub Desktop.
create URL string with query parameters in Node (TypeScript)
/**
*
* @param {string} host
* @param {string} path
* @param {Array<[string, string]>} paramList
* @returns {string}
*/
function createStringifiedURI(host: string, path: string, paramList: Array<[string, string]>): string {
const uri = new URL(
path,
host
);
const queryParamList = new URLSearchParams();
for (const paramItem of paramList) {
queryParamList.append(
paramItem[0],
paramItem[1]
);
}
uri.search = Array.from<[string, string], string>(
queryParamList.entries(),
(queryParamItem: [string, string]) => {
return `${encodeURIComponent(queryParamItem[0])}=${encodeURIComponent(queryParamItem[1])}`;
}
)
.join('&');
return uri.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment