replaceRouterParams.tsx 636 B

12345678910111213141516171819202122232425262728
  1. /**
  2. * Given a route string, replace path parameters (e.g. `:id`) with value from `params`
  3. *
  4. * e.g. {id: 'test'}
  5. */
  6. export default function replaceRouterParams(
  7. route: string,
  8. params: {[key: string]: string | undefined}
  9. ): string {
  10. // parse route params from route
  11. const matches = route.match(/:\w+/g);
  12. if (!matches || !matches.length) {
  13. return route;
  14. }
  15. // replace with current params
  16. matches.forEach(param => {
  17. const paramName = param.slice(1);
  18. if (typeof params[paramName] === 'undefined') {
  19. return;
  20. }
  21. route = route.replace(param, params[paramName] as string);
  22. });
  23. return route;
  24. }