Regex to check whether a string contains only numbers

JavascriptRegex

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

var reg = /^\d+$/;

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

Solution 2 - Javascript

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 - Javascript

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 - Javascript

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"));

Solution 5 - Javascript

^[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.

Solution 6 - Javascript

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);
    });
});

Solution 7 - Javascript

\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

Solution 8 - Javascript

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.

Solution 9 - Javascript

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

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

Solution 10 - Javascript

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

Solution 11 - Javascript

Why dont use something like:

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

Is jquery tested, and the most common case are checked

Solution 12 - Javascript

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

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

Solution 13 - Javascript

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.");
}

Solution 14 - Javascript

Maybe it works:

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

Solution 15 - Javascript

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

Solution 16 - Javascript

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+$/;

Solution 17 - Javascript

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,'')))
    })   

Solution 18 - Javascript

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.

Solution 19 - Javascript

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

Solution 20 - Javascript

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

Solution 21 - Javascript

Number only regex (Updated)

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohanView Question on Stackoverflow
Solution 1 - JavascriptMike SamuelView Answer on Stackoverflow
Solution 2 - JavascriptAbhijeet RastogiView Answer on Stackoverflow
Solution 3 - JavascriptSetthaseView Answer on Stackoverflow
Solution 4 - JavascriptDastagirView Answer on Stackoverflow
Solution 5 - Javascriptuser1299656View Answer on Stackoverflow
Solution 6 - JavascriptDavid LeppikView Answer on Stackoverflow
Solution 7 - JavascriptMuhammad AdeelView Answer on Stackoverflow
Solution 8 - JavascriptJuan LanusView Answer on Stackoverflow
Solution 9 - JavascriptAndrejView Answer on Stackoverflow
Solution 10 - JavascriptjjrvView Answer on Stackoverflow
Solution 11 - Javascriptleonardo reyView Answer on Stackoverflow
Solution 12 - JavascriptEric HodonskyView Answer on Stackoverflow
Solution 13 - JavascriptsrburtonView Answer on Stackoverflow
Solution 14 - JavascriptLPOPYuiView Answer on Stackoverflow
Solution 15 - JavascriptswallaceView Answer on Stackoverflow
Solution 16 - JavascriptProgoView Answer on Stackoverflow
Solution 17 - JavascriptPeter GrahamView Answer on Stackoverflow
Solution 18 - Javascriptshasi kanthView Answer on Stackoverflow
Solution 19 - JavascriptRicheve BebedorView Answer on Stackoverflow
Solution 20 - Javascriptandre123View Answer on Stackoverflow
Solution 21 - JavascriptooozguuurView Answer on Stackoverflow