3
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!

3 Answers 3

10
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];
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

1

regex that would work is

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

I think that's right.

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.