Regex to check whether a string contains only numbers

Johan picture Johan · Jan 25, 2012 · Viewed 807.7k times · Source
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?

Answer

Mike Samuel picture Mike Samuel · Jan 25, 2012
var reg = /^\d+$/;

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