0

Similar to my previous question:

spliting a string in Javascript

The URLs have now changed and the unique number ID is no longer at the end of the URL like so:

/MarketUpdate/Pricing/9352730/Report

How would i extract the number from this now i cannot use the previous solution?

3
  • Either of the solutions below would work for you, so I would advise you to go with the one that's less likely to break in the future. The regex option will break if it encounters 2 or more numbers inside the url, while the split option will break if the number is encountered in a different position (hence, ignored). Commented Jul 23, 2010 at 7:02
  • @Ioannis Karadimas: More precisely, the regex will match the first number that is enclosed in slashes, i. e. it matches 123 in /foo/123/bar/456/baz. It doesn't just match any number, so it works correctly for strings like /foo123/bar/456/baz and matches 456. Commented Jul 23, 2010 at 9:11
  • @Tim Pietzcker: Sorry, I did not properly outline the regex's function. However, I was referring to the general case where it will match 123 in /foo/123/bar/456/. If the desired unique number is 456, I think the problem is evident. It all comes down to the expected general form of the url. Commented Jul 23, 2010 at 9:37

3 Answers 3

6

You could search for

/(\d+)/

and use backreference no. 1 which will contain the number. Note that this requires the number to always be delimited by slashes on both sides. If you also want to match numbers at the end of the string, use

/(\d+)(?:/|$)

In JavaScript:

var myregexp = /\/(\d+)\//;
// var my_other_regexp = /\/(\d+)(?:\/|$)/;
var match = myregexp.exec(subject);
if (match != null) {
    result = match[1];
} else {
    result = "";
}
Sign up to request clarification or add additional context in comments.

Comments

2

If the URLs always look like that, why not use split() ?

var ID = url.split('/')[3];

1 Comment

I'm not sure they will always look like that. They will always have a unique number though.
1
urlstring = "/MarketUpdate/Pricing/9352730/Report"
$str = urlstring.split("/");
alert($str[3]);

This splits the string each time it finds the / symbol and stores it into an array, You can then get each word in the array by using $str[0]

Comments

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.