Check if string contains only digits
But realized that it also allows + and — . Basically, I want to make sure an input contains ONLY digits and no other characters. Since +100 and -5 are both numbers, isNaN() is not the right way to go. Perhaps a regexp is what I need? Any tips?
15 Answers 15
@dewwwald: Some languages implement it differently, but in JavaScript, \d is exactly equivalent to 5 .
@DrorBar I’m sorry for my poor English and let me rephrase it: “if you consider an empty string to be having only digits.”
String.prototype.isNumber = function() console.log("123123".isNumber()); // outputs true console.log("+12".isNumber()); // outputs false
It’s considered bad practice in Javascript to modify prototypes of built-in objects (principle of least surprise, and potential conflicts in future ECMA versions) — consider isNumber = () => /^\d+$/.test(this); instead, and use as console.log(isNumber(«123123));
FWIW, in 2009 when this answer was posted, it was not yet considered a bad practice. Several jQuery competitors that existed then, before jQuery had yet to win out, all practiced prototype extensions.
If you want to even support for float values (Dot separated values) then you can use this expression :
var isNumber = /^\d+\.\d+$/.test(value);
however if you don’t use a float rather int it will return false maybe using «?» after «.\» solved that. I suggest this /^\d+[\.,\,]?\d+$/.test(value) to allow both comma and point decimal (later maybe can transform comma to point)
@Lucke, the regex you suggested will only be able to find numbers with a decimal or higher than 9. If you change the first \d+ to \d*? , it will be able to match 0 — 9, as well as numbers such as .333
Since 2009, this question was always asking how to validate that a string contains only numbers. This post is the correct answer to a different question.
Here’s another interesting, readable way to check if a string contains only digits.
This method works by splitting the string into an array using the spread operator, and then uses the every() method to test whether all elements (characters) in the array are included in the string of digits ‘0123456789’ :
const digits_only = string => [. string].every(c => '0123456789'.includes(c)); console.log(digits_only('123')); // true console.log(digits_only('+123')); // false console.log(digits_only('-123')); // false console.log(digits_only('123.')); // false console.log(digits_only('.123')); // false console.log(digits_only('123.0')); // false console.log(digits_only('0.123')); // false console.log(digits_only('Hello, world!')); // false
Regular expressions
A regular expression (regex for short) allow developers to match strings against a pattern, extract submatch information, or simply test if the string conforms to that pattern. Regular expressions are used in many programming languages, and JavaScript’s syntax is inspired by Perl.
You are encouraged to read the regular expressions guide to get an overview of the available regex syntaxes and how they work.
Description
Regular expressions are a important concept in formal language theory. They are a way to describe a possibly infinite set of character strings (called a language). A regular expression, at its core, needs the following features:
- A set of characters that can be used in the language, called the alphabet.
- Concatenation: ab means «the character a followed by the character b «.
- Union: a|b means «either a or b «.
- Kleene star: a* means «zero or more a characters».
Assuming a finite alphabet (such as the 26 letters of the English alphabet, or the entire Unicode character set), all regular languages can be generated by the features above. Of course, many patterns are very tedious to express this way (such as «10 digits» or «a character that’s not a space»), so JavaScript regular expressions include many shorthands, introduced below.
Note: JavaScript regular expressions are in fact not regular, due to the existence of backreferences (regular expressions must have finite states). However, they are still a very useful feature.
Creating regular expressions
A regular expression is typically created as a literal by enclosing a pattern in forward slashes ( / ):
Regular expressions can also be created with the RegExp() constructor:
const regex2 = new RegExp("ab+c", "g");
They have no runtime differences, although they may have implications on performance, static analyzability, and authoring ergonomic issues with escaping characters. For more information, see the RegExp reference.
Regex flags
Flags are special parameters that can change the way a regular expression is interpreted or the way it interacts with the input text. Each flag corresponds to one accessor property on the RegExp object.
Flag | Description | Corresponding property |
---|---|---|
d | Generate indices for substring matches. | hasIndices |
g | Global search. | global |
i | Case-insensitive search. | ignoreCase |
m | Allows ^ and $ to match newline characters. | multiline |
s | Allows . to match newline characters. | dotAll |
u | «Unicode»; treat a pattern as a sequence of Unicode code points. | unicode |
v | An upgrade to the u mode with more Unicode features. | unicodeSets |
y | Perform a «sticky» search that matches starting at the current position in the target string. | sticky |
The sections below list all available regex syntaxes, grouped by their syntactic nature.
Assertions
Assertions are constructs that test whether the string meets a certain condition at the specified position, but not consume characters. Assertions cannot be quantified.
Asserts that the current position is the start or end of input, or start or end of a line if the m flag is set.
Asserts that the current position is followed or not followed by a certain pattern.
Asserts that the current position is preceded or not preceded by a certain pattern.
Asserts that the current position is a word boundary.
Atoms
Atoms are the most basic units of a regular expression. Each atom consumes one or more characters in the string, and either fails the match or allows the pattern to continue matching with the next atom.
Matches a previously matched subpattern captured with a capturing group.
Matches a subpattern and remembers information about the match.
Matches any character in or not in a set of characters. When the v flag is enabled, it can also be used to match finite-length strings.
Matches any character in or not in a predefined set of characters.
Matches a character that may not be able to be conveniently represented in its literal form.
Matches a specific character.
Matches a previously matched subpattern captured with a named capturing group.
Matches a subpattern and remembers information about the match. The group can later be identified by a custom name instead of by its index in the pattern.
Matches a subpattern without remembering information about the match.
Matches a set of characters specified by a Unicode property. When the v flag is enabled, it can also be used to match finite-length strings.
Matches any character except line terminators, unless the s flag is set.
Other features
These features do not specify any pattern themselves, but are used to compose patterns.
Matches any of a set of alternatives separated by the | character.
Matches an atom a certain number of times.
Escape sequences
Escape sequences in regexes refer to any kind of syntax formed by \ followed by one or more characters. They may serve very different purposes depending on what follow \ . Below is a list of all valid «escape sequences»:
Escape sequence | Followed by | Meaning |
---|---|---|
\B | None | Non-word-boundary assertion |
\D | None | Character class escape representing non-digit characters |
\P | < , a Unicode property and/or value, then > | Unicode character class escape representing characters without the specified Unicode property |
\S | None | Character class escape representing non-white-space characters |
\W | None | Character class escape representing non-word characters |
\b | None | Word boundary assertion; inside character classes, represents U+0008 (BACKSPACE) |
\c | A letter from A to Z or a to z | A character escape representing the control character with value equal to the letter’s character value modulo 32 |
\d | None | Character class escape representing digit characters ( 0 to 9 ) |
\f | None | Character escape representing U+000C (FORM FEED) |
\k | A named backreference | |
\n | None | Character escape representing U+000A (LINE FEED) |
\p | < , a Unicode property and/or value, then > | Unicode character class escape representing characters with the specified Unicode property |
\q | Only valid inside v -mode character classes; represents the string to be matched literally | |
\r | None | Character escape representing U+000D (CARRIAGE RETURN) |
\s | None | Character class escape representing whitespace characters |
\t | None | Character escape representing U+0009 (CHARACTER TABULATION) |
\u | 4 hexadecimal digits; or | Character escape representing the character with the given code point |
\v | None | Character escape representing U+000B (LINE TABULATION) |
\w | None | Character class escape representing word characters ( A to Z , a to z , 0 to 9 , _ ) |
\x | 2 hexadecimal digits | Character escape representing the character with the given value |
\0 | None | Character escape representing U+0000 (NULL) |
\ followed by any other digit character becomes a legacy octal escape sequence, which is forbidden in Unicode-aware mode.
In addition, \ can be followed by some non-letter-or-digit characters, in which case the escape sequence is always a character escape representing the escaped character itself:
- \$ , \( , \) , \* , \+ , \. , \/ , \? , \[ , \\ , \] , \^ , < , \| , >: valid everywhere
- \- : only valid inside character classes
- \! , \# , \% , \& , \, , \: , \; , \ < , \= , \>, \@ , \` , \~ : only valid inside v -mode character classes
The other ASCII characters, namely space character, » , ‘ , _ , and any letter character not mentioned above, are not valid escape sequences. In Unicode-unaware mode, escape sequences that are not one of the above become identity escapes: they represent the character that follows the backslash. For example, \a represents the character a . This behavior limits the ability to introduce new escape sequences without causing backward compatibility issues, and is therefore forbidden in Unicode-aware mode.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Regular Expression only digits and blank spaces
I have a text input and I require that it only accepts digits (0-9) and blank spaces (» «). The current regexp to validate this input is:
Which stands for: one or more groups base on a first group of one or more digits and an optional second group of one or more blank spaces That will only let me introduce values as: 999999 (only digits) or » » (only blank spaces) or 91 08 8510 903 (mix of digits and spaces). But actually, I also can insert aaa or other characters.
3 Answers 3
Dissection
Your regular expression doesn’t accept only letters :
Actually, any character is accepted if the input contains at least one digit :
That being said, let’s skim the fat from your pattern :
"" equals "+" -> ((\d+)(\s+)?)+ "(.+)?" equals ".*" -> ((\d+)\s*)+ useless brackets -> (\d+\s*)+
This result can be translated to : «one or more digits ( \d+ ) followed by zero or more blank spaces ( \s* ), one or more times ( ()+ ), anywhere in the input«. Alternatively, we could say : «at least one digit, anywhere in the input«.
What you need is to replace «anywhere in the input» with «from the beginning to the end of the input». This is allowed by the following special characters : ^ (beginning of input) and $ (end of input). Let’s make a bunch of tests to see how they work :
requirement regex input .test() --------------------------------------------------------------------- must contain at least one digit /\d+/ 'a1a' true must start with at least one digit /^\d+/ '1a' true must start with at least one digit /^\d+/ 'a1' false must end with at least one digit /\d+$/ '1a' false must end with at least one digit /\d+$/ 'a1' true only digits from the beginning to the end /^\d+$/ '1a1' false
Suggestion
Only digits potentially separated by one whitespace : /^\d+( \d+)*$/ .
^ beginning of the input \d+ a digit, one or more times ( \d+)* a whitespace + same as above, zero or more times $ end of the input
var r = /^\d+( \d+)*$/; var isValid = r.test(' 1 '); // false var isValid = r.test('1 1'); // true var isValid = r.test('1 1'); // false