cpeele00
cpeele00

Reputation: 893

Get MVC style route data (URL last word) with JavaScript regex

What I need is to be able to pull the route data out of the MVC URL. I found this solution on SO, however it doesn't suit my needs because I need access to two segments not just one:

var URL = "http://www.xzy.com/AMS/Audit/Agency/Blah";
var number = URL.match(/(\d+)$/g);

This regex code grabs the last segment "Blah". How would I grab "Agency" as well? Considering the last two segments being words.

Upvotes: 1

Views: 308

Answers (1)

acdcjunior
acdcjunior

Reputation: 135802

You can use \w+ to match a word. To make sure the word is the one right before the last, you can use a lookahead: (?=\/\w+$).

var URL = "http://www.xzy.com/AMS/Audit/Agency/1A0A0A1A7A3A9A7";
var agency = URL.match(/(\w+)(?=\/\w+$)/g); // ["Agency"] 
var number = URL.match(/(\w+)$/g); // ["1A0A0A1A7A3A9A7"] 

You could also use RegExp#exec() to get the value as string (not an array like above):

var URL = "http://www.xzy.com/AMS/Audit/Agency/1A0A0A1A7A3A9A7";
var matches = /(\w+)\/(\w+)$/g.exec(URL);
var agency = matches[1]; // Agency
var number = matches[2]; // 1A0A0A1A7A3A9A7

Check demo jsfiddle here for both.

Upvotes: 3

Related Questions