I was using javascript to detect for specific key strokes and while writing the method I thought I’d try regular expressions and the test() method and came up with:
if (/8|9|37|38|46|47|48|49|50|51|52|53|54|55|56|57|96|97|98|99|100|101|102|103|104|105|110/.test(num)) {
// do something if there's a match
}
This doesn’t seem to work 100% as some values seem to make it past the regex test, such as 83. I’ve since moved on, but I’m still curious as to why this didn’t work.
This is the completely wrong way to do it.
To answer the question, the regex is matching part of your string. The string
83passes by matching the8.You need to anchor your regex by putting
^(at the beginning and)$at the end.The correct way to do this is to make an array of valid numbers, and compare using
parseInt.For example:
You’ll need an
indexOffunction for IE: