I have a variable with a certain value, let's say for example var no = 123056
.
Is there a way to determine if that number contains the digit 0, with the help of RegExp
?
Asked
Active
Viewed 1,049 times
0
4 Answers
0
Try something like this.
var no = 12045;
var patt1=/0/; // search pattern
if (no.toString().match(patt1) !== null){
// contains the character 0
alert("character '0' found")
} else {
// does not contain 0
alert("'0' not found")
};
Here is a JSFiddle for it.

StMotorSpark
- 201
- 1
- 7
-
1`g` is a performance penalty here as he's asking only if one exist. and `i`-case insensitive for numbers isn't doing anything. – gdoron Sep 13 '13 at 11:23
-
1What about the second issue? and you should read [`test` vs `match`](http://stackoverflow.com/q/10940137/601179). – gdoron Sep 13 '13 at 11:27
-
Still early in the morning for me, obviously need more coffee. Also very good information in the link. – StMotorSpark Sep 13 '13 at 11:30
-
Thanks, it's my Q&A there... I'll keep the comments here as they have value. – gdoron Sep 13 '13 at 11:32
0
If you really want to use RegExp, yes, it is possible:
/0/
to match a 0. Replace 0 with any other number, including 10+
/[035]/
to match one of 0, 3 OR 5. Replace them with any number you want.
If you want a sequence of a number, add a +
after it.
/(012)+/
will match 1 to infinite consecutive groups of 012, like 012, 012012, 012012012 ...
/012+/
will match 01 and 1 to infinite number of 2, like, 012, 0122, 01222 ...
Also, the best RegExp tool you will probably want to use: http://www.debuggex.com/

Silviu Burcea
- 5,103
- 1
- 29
- 43
0
var no='123056';
var regex=/0/;
if (no.match(regex) == 0) {
alert('hey');
}
This will give you an alert message if the 0 is found.

Daniel
- 56
- 6