Combining solutions above when using express request:
let url=url.parse(req.originalUrl);
let page = url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '';
this will handle all cases like
localhost/page
localhost:3000/page/
/page?item_id=1
localhost:3000/
localhost/
etc. Some examples:
> urls
[ 'http://localhost/page',
'http://localhost:3000/page/',
'http://localhost/page?item_id=1',
'http://localhost/',
'http://localhost:3000/',
'http://localhost/',
'http://localhost:3000/page#item_id=2',
'http://localhost:3000/page?item_id=2#3',
'http://localhost',
'http://localhost:3000' ]
> urls.map(uri => url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '' )
[ 'page', 'page', 'page', '', '', '', 'page', 'page', '', '' ]