I am trying to redirect user to the first page if he enters one that does not exist. For that I need to create new redirectUrl (same except pageNumber is different. Current solution looks similar to this:
// Initial variables
var urlPattern = "/org-status/:orgStatus/date-from/:dateFrom/date-to/:dateTo/:pageNumber";
var currentUrl = "/org-status/all/date-from/any/date-to/09%2F18%2F2019/1566654";
var currentParams = {"orgStatus": "all", "dateFrom": "any", "dateTo": "09/18/2019", "pageNumber": "1566654"}
// variables to alter
var keyToChange = "pageNumber";
var valueToChange = "1";
// Mechanism
currentParams[keyToChange] = valueToChange
var replacedUrl = urlPattern;
for (var [key, value] of Object.entries(currentParams)) {
redirectUrl = redirectUrl.replace(`:${key}`, encodeURIComponent(value))
}
// redirectUrl === "/org-status/all/date-from/any/date-to/09%2F18%2F2019/1";
Current mechanism is using only urlPattern and currentParams from initial variables. And that can lead to some future errors. For example:
- Some of the parameters are not defined in
currentParamsso result can endup with missing values like:"/org-status/:orgStatus/date-from/:dateFrom/date-to/09%2F18%2F2019/1" - Date format is changed (
mm/dd/yyyytoyyyy-mm-dd) which can lead to server error or worse - badly interpreted search parameter.
To avoid that it would be better to use only urlPattern and currentUrl variables instead (not to use currentParams). And I cannot proper way to achieve that.