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

Solution 1:

var reg = /^\d+$/;

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

Solution 2:

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].

Solution 3:

This one will allow also for signed and float numbers or empty string:

var reg = /^-?\d*\.?\d*$/

If you don't want allow to empty string use this one:

var reg = /^-?\d+\.?\d*$/

Solution 4:

var validation = {
    isEmailAddress:function(str) {
        var pattern =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        return pattern.test(str);  // returns a boolean
    },
    isNotEmpty:function (str) {
        var pattern =/\S+/;
        return pattern.test(str);  // returns a boolean
    },
    isNumber:function(str) {
        var pattern = /^\d+$/;
        return pattern.test(str);  // returns a boolean
    },
    isSame:function(str1,str2){
        return str1 === str2;
    }
};   

alert(validation.isNotEmpty("dff"));
alert(validation.isNumber(44));
alert(validation.isEmailAddress("[email protected]"));
alert(validation.isSame("sf","sf"));