-2

How do I get the customerid path variable from the following URL:

/customers/{customerid}/agreements/{agreementid}

The customerid path variable can vary in length, so I want everything between /customers/ and /agreements...

I have searched the net for a solution and tried to construct some RegEx myself but so far unsuccesfully.

  • 2
    Hello, welcome to SO. What have you tried so far? Please [edit](https://stackoverflow.com/posts/54929318/edit) your question and add all the relevant code, telling us what doesn't work, why, what was the expected output and what happened instead. Don't forget to include the full stack trace if you are getting any error. – BackSlash Feb 28 '19 at 15:41

1 Answers1

0

If you know the order of the elements in the URL is fixed (I.e. there is nothing before the /customers segment, like a site/languages prefixes - /uk), you can just split the URL and grab the 2nd element in the resulting array. Like so:

var urlParts = url.split('/');
var customerId = urlParts[1]; // Arrays positions start at 0.

Or more elegantly:

var customerId = url.split('/')[1];

If you're not sure about the URL structure, but know that the customer ID is always right after the /customers segment, you can use regular expression to extract it.

UPDATE: I just realized you were referring to Java, but the above solutions are still valid. Here's a similar question about URL splitting in Java: In java, what's the best way to read a url and split it into its parts?

benPesso
  • 79
  • 3