1

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:

  1. Some of the parameters are not defined in currentParams so result can endup with missing values like: "/org-status/:orgStatus/date-from/:dateFrom/date-to/09%2F18%2F2019/1"
  2. Date format is changed (mm/dd/yyyy to yyyy-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.

The Hog
  • 572
  • 5
  • 17
  • `new RegExp(keyToChange, 'g')` (if it's not just text you will need to escape regex operators) if you need more the one, if there is only one use the string instead of regex. – jcubic Sep 11 '19 at 08:44
  • yeah, though the problem is that `keyToChange` is from the pattern, not the string I actually want to alter. So the regex itself have to include the pattern somehow – The Hog Sep 11 '19 at 08:55
  • Looks like you are looking to create a regex, but do not know where to get started. Please check [Reference - What does this regex mean](https://stackoverflow.com/questions/22937618) resource, it has plenty of hints. Also, refer to [Learning Regular Expressions](https://stackoverflow.com/a/2759417/3832970) post for some basic regex info. Once you get some expression ready and still have issues with the solution, please edit the question with the latest details and we'll be glad to help you fix the problem. – Wiktor Stribiżew Sep 11 '19 at 08:56
  • Ok, then what you need is to create regex from your pattern, replacing `:key` with `([^/]+)` and wrap non keywords with parenthesis as well and in replacement you recreate URL with one replacement that look something likes this `'$1/$2/$3/$4/123'` where $1 is index of the parenthesis group (it starts from 1). – jcubic Sep 11 '19 at 09:02

0 Answers0