Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to check whether a string contains only numbers [duplicate]

hash = window.location.hash.substr(1); var reg = new RegExp('^[0-9]$'); console.log(reg.test(hash)); 

I get false on both "123" and "123f". I would like to check if the hash only contains numbers. Did I miss something?

like image 662
Johan Avatar asked Jan 25 '12 22:01

Johan


People also ask

How do I check if a string contains only numbers?

Check if String Contains Only Numbers using isdigit() method Python String isdigit() method returns “True” if all characters in the string are digits, Otherwise, It returns “False”.

What is the regex for numbers only?

\d for single or multiple digit numbers To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

How do you check if a regex matches a string?

If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() . If you only want the first match found, you might want to use RegExp.prototype.exec() instead.

How do I match a number in regex?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.


2 Answers

var reg = /^\d+$/; 

should do it. The original matches anything that consists of exactly one digit.

like image 185
Mike Samuel Avatar answered Oct 02 '22 14:10

Mike Samuel


As you said, you want hash to contain only numbers.

const reg = new RegExp('^[0-9]+$'); 

or

const reg = new RegExp('^\d+$') 

\d and [0-9] both mean the same thing. The + used means that search for one or more occurring of [0-9].

like image 26
Abhijeet Rastogi Avatar answered Oct 02 '22 15:10

Abhijeet Rastogi