Alex Rivera | Logout

Javascript regular expression match on string followed by number?

Asked 2009-08-11T20:23:57.013
21

I have a string of the format: string:num where num is any number but string is a known string that I need to match on. I'd like to have this in an if statement as:

if( it matches 'string:' followed by a number) {
   //do something
}
Edit
Report

1 Answer

47

You want ...

if (stringYouHave.match(/^string:([0-9]+)$/)) {
    // do something
}

This includes:

  1. ^ beginning of the string
  2. string: the literal "string:" you mentioned
  3. (.....) This subexpression, which you can refer to later if you need to know which number is in the string (though in this particular case, you could also just replace 'string:' with '')
  4. [0-9] a character between 0 and 9 (i.e., a digit)
  5. + Must have at least one "of those" (i.e., digits mentioned above), but can have any number
  6. $ end of the string
answered 2009-08-11T20:25:32.597

Your Answer