456
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?

2
  • 3
    According to W3schools ^ only negates sequences when inside the bracket, so [^0-9] refers to non-digits, but ^[0-9] does indicate "line beginning" Commented May 11, 2016 at 20:43
  • you can check my answer. In which I placed all validation in the same place with a proper error message. Visit my Link stackoverflow.com/a/78050480/4335210 Commented Feb 23, 2024 at 22:28

21 Answers 21

736
var reg = /^\d+$/;

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

Sign up to request clarification or add additional context in comments.

17 Comments

@vsync, because \d in a single quoted string is the letter 'd'. Try running '/^\d+$/' === '/^d+$/' in your JavaScript console. You need to double-escape when embedding a RegExp in a string: eval('/^\\d+$/')
It doesn't take into account negative number.
@GiuseppePes. True. It also doesn't handle real numbers, complex numbers, quaternions, etc. The question related to counting numbers and so does my answer.
/^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/
@D_N. Fair enough. To your original point, yes 008 is an error token in many PLs because it starts like an octal literal, but in standard mathematical notation base ₁₀ is implied. I don't know which the asker wanted and if I were to reject malformed octal, I should match valid hex and decide whether to include Python3/Java numbers like 123_456 or C++ 123'456. \d+ seems like a middle ground in the absence of more context like a specific programming or human language and was strongly suggested by the author's first attempt.
|
176

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

1 Comment

This is not entirely true, [0-9] and \d are NOT the same, \d also matches numeric characters from other character sets such as hebrew and chinese.
93

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*$/

8 Comments

Your second regex was really helpful. It just got stuck at validating a number like .378 Could you kindly let me know how to tweak /^-?\d+\.?\d*$/ so that it validates .378 as well
Change + into *: ^-?\d*\.?\d*$. + mean that you looking for at least one number on front, * looking for zero or many numbers.
for float better use /^-?\d+(\.\d+)?$/
If you don't want to allow empty but want to allow syntax like .25 use var reg = /^-?\d*[\.]?\d+$/
This thread was extremely helpful! Here's a regular expression I came up with that handles plus and minus signs, as well as E notation. ^[-+]?\d*\.?\d*(\d+[eE][-+]?)?\d+$
|
74
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+\.?\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"));

3 Comments

It doesn't support float
@WeijingJayLin don't worry bro, new version of this library will fix the bug
I think that the isNumber pattern should be => /^\d*\.?\d+$/ so, it will accept .9 and will not accept 9.
36
^[0-9]$ 

...is a regular expression matching any single digit, so 1 will return true but 123 will return false.

If you add the * quantifier,

^[0-9]*$

the expression will match arbitrary length strings of digits and 123 will return true. (123f will still return false).

Be aware that technically an empty string is a 0-length string of digits, and so it will return true using ^[0-9]*$ If you want to only accept strings containing 1 or more digits, use + instead of *

^[0-9]+$

As the many others have pointed out, there are more than a few ways to achieve this, but I felt like it was appropriate to point out that the code in the original question only requires a single additional character to work as intended.

Comments

31

This is extreme overkill for your purpose:

const numberReSnippet = "NaN|-?((\d*\.\d+|\d+)([Ee][+-]?\d+)?|Infinity)";
const matchOnlyNumberRe = new RegExp("^("+ numberReSnippet + ")$");

To my knowledge, this matches all the variations on numbers that Java and JavaScript will ever throw at you, including "-Infinity", "1e-24" and "NaN". It also matches numbers you might type, such as "-.5".

As written, numberReSnippet is designed to be dropped into other regular expressions, so you can extract (or avoid) numbers. Despite all the parentheses, it contains no capturing groups. Thus "matchOnlyNumberRe" matches only strings that are numbers, and has a capturing group for the entire string.

Here are the Jasmine tests, so you can see what it does and doesn't handle:

describe("Number Regex", function() {
    const re = matchOnlyNumberRe;
    it("Matches Java and JavaScript numbers", function() {
        expect(re.test(         "1")).toBe(true);
        expect(re.test(       "0.2")).toBe(true);
        expect(re.test(     "0.4E4")).toBe(true);  // Java-style
        expect(re.test(       "-55")).toBe(true);
        expect(re.test(      "-0.6")).toBe(true);
        expect(re.test(  "-0.77E77")).toBe(true);
        expect(re.test(      "88E8")).toBe(true);
        expect(re.test(       "NaN")).toBe(true);
        expect(re.test(  "Infinity")).toBe(true);
        expect(re.test( "-Infinity")).toBe(true);
        expect(re.test(     "1e+24")).toBe(true);  // JavaScript-style
    });
    it("Matches fractions with a leading decimal point", function() {
        expect(re.test(        ".3")).toBe(true);
        expect(re.test(       "-.3")).toBe(true);
        expect(re.test(     ".3e-4")).toBe(true);
    });
    it("Doesn't match non-numbers", function() {
        expect(re.test(         ".")).toBe(false);
        expect(re.test(        "9.")).toBe(false);
        expect(re.test(          "")).toBe(false);
        expect(re.test(         "E")).toBe(false);
        expect(re.test(       "e24")).toBe(false);
        expect(re.test(   "1e+24.5")).toBe(false);
        expect(re.test("-.Infinity")).toBe(false);
        expect(re.test(      "8|24")).toBe(false);
    });
});

4 Comments

IsNumber will only check if it's integer, as its name it should check if it's number in general (double, integer). I think this answer is more comprehensive than others.
The part [E|e][+|-]? is incorrect. It looks like you were thinking (?:E|e)(?:\+|-)? and forgot to drop the | when you made it into character sets. You need the | when you use groupings to specify alternatives, but in a character set, the listed choices are automatically alternatives to each other and | has no special meaning. So something like [E|e] allows E, e and the character |.
So the correct regex (without non-catching groups and double slashes) is: /NaN|-?((\d*\.\d+|\d+)([Ee][+-]?\d+)?|Infinity)/. I switched up the floats and ints so the expression gets more greedy.
Thanks; I've changed the regex to @SimonZyx's, and added a unit test to confirm that the original was buggy.
19

\d will not match the decimal point. Use the following for the decimal.

const re = /^\d*(\.\d+)?$/
'123'.match(re)       // true
'123.3'.match(re)     // true
'123!3'.match(re)     // false

3 Comments

Although a good remark, this regex will also match a string containing only dots (e.g. '.....'.match(re) //true"
not everything shud be left to regex :) there are preconditions to preconditions, unknowns to unknowns.
nicely said, sir :) just as a followup, we can use /^\d*(\.\d+)?$/ to have a better match for positive floating numbers
12

This function checks if it's input is numeric in the classical sense, as one expects a normal number detection function to work.

It's a test one can use for HTML form input, for example.

It bypasses all the JS folklore, like tipeof(NaN) = number, parseint('1 Kg') = 1, booleans coerced into numbers, and the like.

It does it by rendering the argument as a string and checking that string against a regex like those by @codename- but allowing entries like 5. and .5

function isANumber( n ) {
    var numStr = /^-?(\d+\.?\d*)$|(\d*\.?\d+)$/;
    return numStr.test( n.toString() );
}

not numeric:
Logger.log( 'isANumber( "aaa" ): ' + isANumber( 'aaa' ) );
Logger.log( 'isANumber( "" ): ' + isANumber( '' ) );
Logger.log( 'isANumber( "lkjh" ): ' + isANumber( 'lkjh' ) );
Logger.log( 'isANumber( 0/0 ): ' + isANumber( 0 / 0 ) );
Logger.log( 'isANumber( 1/0 ): ' + isANumber( 1 / 0 ) );
Logger.log( 'isANumber( "1Kg" ): ' + isANumber( '1Kg' ) );
Logger.log( 'isANumber( "1 Kg" ): ' + isANumber( '1 Kg' ) );
Logger.log( 'isANumber( false ): ' + isANumber( false ) );
Logger.log( 'isANumber( true ): ' + isANumber( true ) );

numeric:
Logger.log( 'isANumber( "0" ): ' + isANumber( '0' ) );
Logger.log( 'isANumber( "12.5" ): ' + isANumber( '12.5' ) );
Logger.log( 'isANumber( ".5" ): ' + isANumber( '.5' ) );
Logger.log( 'isANumber( "5." ): ' + isANumber( '5.' ) );
Logger.log( 'isANumber( "-5" ): ' + isANumber( '-5' ) );
Logger.log( 'isANumber( "-5." ): ' + isANumber( '-5.' ) );
Logger.log( 'isANumber( "-.5" ): ' + isANumber( '-5.' ) );
Logger.log( 'isANumber( "1234567890" ): ' + isANumber( '1234567890' ));

Explanation of the regex:

/^-?(\d+\.?\d*)$|(\d*\.?\d+)$/  

The initial "^" and the final "$" match the start and the end of the string, to ensure the check spans the whole string. The "-?" part is the minus sign with the "?" multiplier that allows zero or one instance of it.

Then there are two similar groups, delimited by parenthesis. The string has to match either of these groups. The first matches numbers like 5. and the second .5

The first group is

\d+\.?\d*

The "\d+" matches a digit (\d) one or more times.
The "\.?" is the decimal point (escaped with "\" to devoid it of its magic), zero or one times.

The last part "\d*" is again a digit, zero or more times.
All the parts are optional but the first digit, so this group matches numbers like 5. and not .5 which are matched by the other half.

3 Comments

4.5.3 is true for your regex
/^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/
@RicheveBebedor Nice, your version ads the exponent thing, which is fine for those cases where it's needed, like in engineering or astronomical inputs. I omitted it on purpose seeking a regexp that would return the minimum set of valid money input values.
8

If you need just positive integer numbers and don't need leading zeros (e.g. "0001234" or "00"):

var reg = /^(?:[1-9]\d*|\d)$/;

Comments

8

If the numbers aren't supposed to be absurdly huge, maybe use:

new RegExp(
    '^' +                           // No leading content.
    '[-+]?' +                       // Optional sign.
    '(?:[0-9]{0,30}\\.)?' +         // Optionally 0-30 decimal digits of mantissa.
    '[0-9]{1,30}' +                 // 1-30 decimal digits of integer or fraction.
    '(?:[Ee][-+]?[1-2]?[0-9])?' +   // Optional exponent 0-29 for scientific notation.
    '$'                             // No trailing content.
)

This tries to avoid some scenarios, just in case:

  • Overflowing any buffers the original string might get passed to.
  • Slowness or oddities caused by denormal numbers like 1E-323.
  • Passing Infinity when a finite number is expected (try 1E309 or -1E309).

Comments

8

Why dont use something like:

$.isNumeric($(input).val())

Is jquery tested, and the most common case are checked

2 Comments

You ask why not just use jQuery. Here are reasons why not. 1. If your code is not already using jQuery, add jQuery only to check that values are numeric? I don't think so. 2. Suppose you already have a framework in place that tokenizes by running through a list of regular expressions. If you don't use a regular expression for numbers, you have to write a special case for it: iterate through the list of regular expressions and then also check with jQuery whether the token is numeric. Complicates the code. 3. If you need to allow for NaN or the infinities, $.isNumeric won't work.
It's 2018. Any response that suggests jQuery as the solution when it's not explicitly asked should be ignored.
6

Maybe it works:

let a = "1234"
parseInt(a) == a // true
let b = "1234abc"
parseInt(b) == b // false

2 Comments

fails if you have leading zeroes, e.g. for a zip code. parseInt('01234') != 01234.
@PeterHollingsworth Thanks! I haven't know that.
5

You need the * so it says "zero or more of the previous character" and this should do it:

var reg = new RegExp('^\\d*$');

Comments

5

Simple Regex javascript

var cnpj = "12.32.432/1-22";
var rCnpj = cnpj.replace(/\D/gm,"");
console.log(cnpj);

*Result:

1232432122

Checks for only numbers:

if(rCnpj === cnpj){
   return true;
}

Simple example

if("12.32.432/1-22".replace(/\D/gm,"").length > 0){
   console.log("Ok.");
}

2 Comments

This answer does not check whether a string contains only numbers. Instead, it removes all characters but numbers. You can make your answer applicable to the question by checking to see if the resulting value is strictly equivalent to the original value: original_value === resulting_value // Only Numbers.
Thank you! It has been altered.
3

You could also use the following methods but be aware of their internal implementation and/or return values.

1A isNaN(+'13761123123123'); // returns true
1B isNaN(+'13761123123ABC'); // returns false

2A ~~'1.23'; // returns 1
2B ~~'1.2A'; // returns 0

For 1A & 1B the string is first type coerced using the + operator before being passed to the isNaN() function. This works because a number types that include non-numeric values return NaN. There are considerations with the isNaN()'s implementation details which is documented here. One consideration is if a boolean value is passed as isNaN(+false|true) are coerced to their numeric equivalents and thus false is returned but one might expect the function to return true since the boolean value isn't numeric in the sense of what we are testing.

For 2A & 2B it's worth noting that finding the complement of the number requires the given value in question to be within the range the values of a signed 32 bit integer which can be referenced in the spec.

My personal preference, although it could be argued to be less readable since they include the unary operator, is 1A & 1B because of the speed and conciseness.

Perf https://jsperf.com/numeric-string-test-regexvsisnan/1

Comments

0

I see you have already gotten a lot of answers, but if you are looking for a regular expression that can match integers and floating point numbers, this one will work for you:

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

2 Comments

This won't match .123 or any negative number. Use /^-?\d*\.?\d+$/ instead.
It was edited, now it will.
0

On input, if you want to filter out other characters and only show numbers in the input field, you could replace the value of the field on keyup:

    var yourInput = jQuery('#input-field');
    yourInput.keyup(function() {
        yourInput.val((yourInput.val().replace(/[^\d]/g,'')))
    })   

Comments

-1
/^[\+\-]?\d*\.?\d+(?:[Ee][\+\-]?\d+)?$/

Comments

-1

If you want to match the numbers with signed values, you can use:

var reg = new RegExp('^(\-?|\+?)\d*$');

It will validate the numbers of format: +1, -1, 1.

Comments

-2
var pattern = /[0-9!"£$%^&*()_+-=]/;

This tries to avoid some scenarios, just in case:

Overflowing any buffers the original string might get passed to. Slowness or oddities caused by denormal numbers like 1E-323. Passing Infinity when a finite number is expected (try 1E309 or -1E309).

1 Comment

How does your pattern achieve those stated goals?
-4

Number only regex (Updated)

 var reg = new RegExp('[^0-9]','g');

2 Comments

it's should delete the '/' as new RegExp('[^0-9]','g');
This regexp is wrong, as it is matching everything, but not numbers... You should remove ^ from square brackets if it has to do what you intended... And syntax is wrong as @vagabond mentioned it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.