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
}
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
}
You want ...
if (stringYouHave.match(/^string:([0-9]+)$/)) {
// do something
}
This includes:
^
beginning of the stringstring:
the literal "string:" you mentioned(.....)
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 ''
)[0-9]
a character between 0
and 9
(i.e., a digit)+
Must have at least one "of those" (i.e., digits mentioned above), but can have any number$
end of the stringThe above is good for integer numbers; if you want floating point numbers, or even scientific notation (as understood in C-like languages), you'll want something like this:
if (stringYouHave.match(/^string:[+-]?[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?$/))
{
// do something
}
You can remove the first [+-]? if you don't care about sign, the (.[0-9]+)? if you don't care about floating points, and the ([eE][+-]?[0-9]+)? if you don't care about scientific notation exponents. But if there's a chance you DO want to match those, you want to include them as optional in the regex.
if(teststring.match(new RegExp("^" + knownstring + ":\d+$"))) {
// some code
}
if(!!"string:5456".match(/^string:\d+$/)) { ... }
Number is a integer in the example above.
If you want only to check if the input string matches the pattern, you can use the RegExp.test function:
if (/^string:[0-9]+$/.test(input)){
//..
}
or with the String.search function:
if (input.search(/^string:[0-9]+$/) != -1){
//..
}
If you want to validate and get the number:
var match = input.match(/^string:([0-9]+)$/),
number;
if (match){
number = +match[1]; // unary plus to convert to number
// work with it
}