Denis Ivanov
Denis Ivanov

Reputation: 905

express js: Conditional route parameters with RegEx

I need to match a route that has this form: /city-state-country

Where city can be in formats: san-francisco (multiword separated by '-') or newtown (single word).

And also some countries have state missing, so '-state' param in route should be optional.

How can I strictly match match my route pattern, meaning that it will take either 2 or 3 parameters separated by '-'?

I had something like this:

app.get(/([A-Za-z\-\']+)-([A-Za-z\']+)-([A-Za-z\']+)/, routes.index_location);

but, it didn't work.

Ultimately, cases like these should not work:

/c/san-jose-ca-us
/san-jose-ca-us-someweirdstuff

Upvotes: 0

Views: 915

Answers (3)

Oleg Vdovenko
Oleg Vdovenko

Reputation: 1

If you only want to keep your information on 1 level hierarchy you can try the underscore delimiter. So, your url be like: city_state_country

Upvotes: 0

Keith
Keith

Reputation: 994

Actually, there is a way. But, it would take a multi step process. In the first pass, replace all two letter states (since they are optional) with a different delimiter. In the second pass, replace all of the countries with a different delimiter so you can recognize cities. In the third pass, replace all city dashes with some other character and add back the states and countries with dash delimiters. In the final pass, replace your cities with a different delimiter with the delimiter you expect.

For instance:

  1. replace /-(al|ca|az...)/ with ~$1 san-jose-ca-us = san-jose~ca-us
  2. replace /-(.+)$/ with ~$1 san-jose~ca-us = san-jose~ca~us
  3. replace /-/ with *$1 san-jose~ca~us = san*jose~ca~us
  4. replace /~/ with - san*jose~ca~us = san*jose-ca-us

etc.

Upvotes: 0

alex
alex

Reputation: 12265

san-jose-ca-us-someweirdstuff can be parsed as san-jose-ca (city) - us (state) - someweirdstuff (country), so it's perfectly valid case

Unless you missed something, the task is impossible in general. We know that us isn't a state, but regexp doesn't.

You can try to limit an amount of dashes in the city to one, or enumerate all possible countries, or do something like that... Anyway, this has nothing to do with regular expressions, really.

Upvotes: 1

Related Questions