Skip to content

Instantly share code, notes, and snippets.

@skulptur
Created February 1, 2021 13:43
Show Gist options
  • Save skulptur/ea7b80a207b48cc635d64afdbc5e80ba to your computer and use it in GitHub Desktop.
Save skulptur/ea7b80a207b48cc635d64afdbc5e80ba to your computer and use it in GitHub Desktop.
Util for replacing params in a React router style url config
/**
* Builds a path from a template and replaces the params
*
* @function createPath
* @param path The configured path (e.g. /foo/:bar)
* @param params The param values you want to replace it with (e.g. \{bar: 'baz'\})
* @param search Any query string values that you want to add
* @category routing
*/
export const createPath = (
path: string,
params: { [key: string]: string } = {},
search: string = '',
) =>
path
// first replace all params
.replace(/:(\w+)/g, (match, param) => {
if (typeof params[param] !== 'undefined') {
return params[param] || '';
}
return match;
})
// remove unresolved optional parts
.replace(/\/:(\w+)\?/g, () => '')
// remove ? from resolved optional parts
.replace(/([^:]+?)\?/g, (match, part) => part)
// do we still have params left?
.replace(/:(\w+)/g, (match, param) => {
throw new Error(`Param "${param}" is missing in params ${params}, needed for '${path}'`);
}) + search;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment