-2

This is probably a super simple RegExp, but I'm really bad and can only get so far. So can some one help please :)

I want to test for a specific string that contains a number. So for example, string/[0-9]/[*]. So some examples:

/string/12 = true  
/string/0/ = true  
/string/123/anything = true  

/string123 = false  
/string/123abc = false

So far, all I have got to it:

RegExp('/string/[0-9]').test('/string/123')

But this doesn't work for all the scenarios above.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
keogh
  • 458
  • 1
  • 3
  • 14

1 Answers1

1

It looks like you need to ensure that after /string/, there are one or more digits, followed by either / or the end of the string:

const validate = str => console.log(/^\/string\/\d+(?:\/|$)/.test(str));

[
  '/string/12',
  '/string/0/',
  '/string/123/anything',

  '/string123',
  '/string/123abc',
].forEach(validate);

Your original regex only checked that there was a single digit after the /.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • How would I use this in a `match()` expression to extract the number in the string? So for `/string/123/anything`, How would I use `match()` to retrieve the `123`? – keogh Nov 27 '18 at 00:34
  • Surround the digits in a group, and then continually use `exec` until there are no more matches, see https://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression . Unfortunately there's no simple built-in way to extract groups like that – CertainPerformance Nov 27 '18 at 00:52