Title: In Express.js how would I write a route/regex to capture all US states?
Tags: regex;node.js;express
Question: At the moment I have the states in a string as follows:
var states = 'AL|AK|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL...';
I would like to capture
mydomain.com/CA/more-stuff
Into two separate parameters.  The first one with the state information, the second one with the additional.  I know how to get the additional information:
app.get('/' ??? + '/:additional', ...);
How can I capture the state information?
Comment: Why not to use "/:state/:additional" and then validate the state internally that would allow you to return a nice error object for invalid input?


Here is another answer: Try this one
var states = 'AL|AK|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL...';
app.get('/:state('+ states + ')/:additional', function(req,res,next){
res.send('state:'+req.params.state+',additional:'+req.params.additional);
I've tested it and it should work as You requested :)

Here is another answer: If you define it as a parameter in the path...
app.get('/:stateabbr/:additional', ...);
You can validate it with app.param():
app.param('stateabbr', function (req, res, next, abbr) {
var stateAbbrs = /AL|AK|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|../i
if (stateAbbrs.test(abbr)) {
next()
} else {
next(new Error('Unrecognized State abbreviation.'));

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2012:00:08/27/12', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<regex><node.js><express>', 'Title': 'In Express.js how would I write a route/regex to capture all US states?', 'ViewCount': 869, 'id': 12139082, 'user_AboutMe': '', 'user_AccountId': 995848.0, 'user_DisplayName': 'Hoa', 'user_Reputation': 19234.0, 'user_Views': 1831.0, 'user_id': 1011816.0}}