DEV Community

Alaa Mohammad
Alaa Mohammad

Posted on

Create a custom function to generate a URL from given parameters (with TS support) đź’»

We can achieve this using two options:

First option:

const urlGenerator = ( baseUrl: string, pathName: string, searchParamsArray: Array<Record<string, string | number>> ) => { const validSearchParams = searchParamsArray.filter((param) => { const [_, value] = Object.entries(param)[0]; // We can put here any condition on the value return value; }); const sortedSearchParams = validSearchParams.sort((a, b) => { const [aKey] = Object.entries(a)[0]; const [bKey] = Object.entries(b)[0]; if (aKey > bKey) { return 1; } else if (aKey < bKey) { return -1; } else return 0; }) const searchParams = sortedSearchParams .map((param) => { const [key, value] = Object.entries(param)[0]; return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; }) .join("&"); const url = `${baseUrl}${pathName}?${searchParams}`; return url; }; const resultUrl = urlGenerator("http://example.com", "/", [ { width: 200 }, { height: 250 }, { locale: "en" }, { toolbar_bg: "" }, { interval: "3h" }, { search: "react19" }, ]); console.log("resultUrl=", resultUrl); // resultUrl= http://example.com/?height=250&interval=3h&locale=en&search=react19&width=200 
Enter fullscreen mode Exit fullscreen mode

Second option:
By using URLSearchParams as the following

const urlGenerator = ( baseUrl: string, pathName: string, searchParamsArray: Array<Record<string, string>> ) => { const validSearchParams = searchParamsArray.filter((param) => { const [_, value] = Object.entries(param)[0]; // We can put here any condition on the value return value; }); const sortedSearchParams = validSearchParams.sort((a, b) => { const [aKey] = Object.entries(a)[0]; const [bKey] = Object.entries(b)[0]; if (aKey > bKey) { return 1; } else if (aKey < bKey) { return -1; } else return 0; }).map((param)=>Object.entries(param)[0]); const searchParams=new URLSearchParams(Object.fromEntries(sortedSearchParams)) const url = `${baseUrl}${pathName}?${searchParams.toString()}`; return url; }; const resultUrl = urlGenerator("http://example.com", "/", [ { width: "200" }, { height: "250" }, { locale: "en" }, { toolbar_bg: "" }, { interval: "3h" }, { search: "react19" }, ]); console.log("resultUrl=", resultUrl); // resultUrl= http://example.com/?height=250&interval=3h&locale=en&search=react19&width=200 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)