I need to check if the first 6 digits of a number are from 222100-272099. This is in JavaScript, and I'm not sure how to go about implementing it. My initial thought was something like: match(/^2[2-7][0-9]$/), but I'm not sure how to specify this range correctly.
Asked
Active
Viewed 100 times
-2
-
(/^2[2-7][0-9]{4}$/) might be what you are looking for? {number} is how many of the previous character you want. If that does the trick I'll write up an answer. – sniperd Jul 24 '17 at 13:51
-
Welcome to Stack Overflow. Please read first in the help center, how to ask a good question on this forum: https://stackoverflow.com/help/how-to-ask. So we can better unterstand your question and can help you with your problems. – Julian Schmuckli Jul 24 '17 at 13:51
-
1[Now you have two problems](https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/). – Phylogenesis Jul 24 '17 at 13:53
-
@sniperd Your regex would also match 279000, which is not in the range.. but that's just not a job for regexs. – idmean Jul 24 '17 at 13:53
-
Oh, right! Ha. I should probably read the whole question :) – sniperd Jul 24 '17 at 13:56
2 Answers
3
You shouldn’t really use a RegEx for that. It is better to substring the string and then compare:
const n = Number.parseInt(str.substr(0, 6), 10);
if (222100 <= n && n <= 272099) {
// ...

idmean
- 14,540
- 9
- 54
- 83
-
Be careful with this. It will also match `22210a` or `25ujid`. You may want to run it through `parseInt()` too. – Phylogenesis Jul 24 '17 at 13:57
-
1Really? `const str = '22210a'; const n = str.substr(0, 6); 222100 <= n && n <= 272099` returns false for me. – idmean Jul 24 '17 at 13:58
-
That's a much more ideal solution. It worked perfectly - Thanks! – amoonshapedpool Jul 24 '17 at 14:08
-
No, you're right. The comparison operators [coerce both sides to `Number` if they are not both `String`s](https://stackoverflow.com/a/14687877/2347483). – Phylogenesis Jul 24 '17 at 14:17
0
Regular expressions are for pattern matching in strings: Wikipedia: Regular expression
You can use JavaScript's parseInt() function to turn your 6 numeric character string into a number that can be used to do a simple greater than/less than check. W3C: parseInt()

Brian
- 41
- 1
- 8