1

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for responding! I should clarify, the second segment is a word as well..I just used that above as an example. I wasn't aware it would be different for numbers. Any idea as to how to grab them both if they are both words? Thx again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.