stormist
stormist

Reputation: 5925

Extracting numbers from a url using javascript?

var exampleURL = '/example/url/345234/test/';
var numbersOnly = [?]

The /url/ and /test portions of the path will always be the same.

Note that I need the numbers between /url/ and /test. In the example URL above, the placeholder word example might be numbers too from time to time but in that case it shouldn't be matched. Only the numbers between /url/ and /test.

Thanks!

Upvotes: 3

Views: 4155

Answers (3)

Rob
Rob

Reputation: 8195

var exampleURL = '/example/url/345234/test/';

// this will remove all non-numbers
var numbers = exampleURL.replace(/[\D]/g, '');

// or you can split the string and take only that 3rd bit
var numbers = exampleURL.split(/\//)[3];

// or match with a regex
var numbers = exampleURL.match(/\/(\d+)\/test\//)[1];

Upvotes: 10

T.J. Crowder
T.J. Crowder

Reputation: 1075537

Something along these lines:

var result;
result = value.match(/\/url\/([0-9]+)\/test/);
// use result[1] to get the numbers (the first capture group)

That relies on the /url/ and /test bits, since you said they were reliable. More generally, this will match the first run of digits in the string:

var result;
result = value.match(/[0-9]+/);
// use result[0] (not result[1]), which is the total match

The MDC page on regular expressions is pretty useful.

Note: Instead of [0-9] above, you can use \d which stands for "digit". I don't because my regex-fu is weak and I can never remember it (and when I do, I can never remember whether it's all digits or all non-digits [which is \D -- you see my confusion]. I find [0-9] really clear when I read it later. Others may find \d clearer, but for me, I like the explicit-ness of listing the range.

Upvotes: 5

zellio
zellio

Reputation: 32524

regex that would work is

matches = exampleURL.match('/\/.+\/url/([0-9]+)\/test\//');

I think that's right.

Upvotes: 1

Related Questions