How to check if string contains only digits in JavaScript

Check if String contains only Digits in JavaScript

In this article, you’ll learn how to check if string contains only digits in JavaScript by using regular expressions and the .search() and .test() functions. Lets read it now.

Check if string contains only digits in JavaScript

So visually, to check if something is a number, you see if it only contains digits. However, while JavaScript can check if something contains digits (with a regular expression (/.../) ), it won’t directly tell you if it also contains characters or space. So instead of looking for numbers, you can check if the string contains anything, not a number and declare that string only contains digits if false.

Though, first, it is required that we understand what the regular expression is and works. 

Understanding Regular Expressions

A regular expression or “regex” for shorthand, is a pattern to identify characters or a combination of them in a string. A regex is symbolized by two forward slashes ("/.../") and can have special characters to identify special patterns.

Additionally, there’s the RegExp class, which should only be used when the regex can change.

There are 5 types of special characters:

  • Assertions: Indicates conditions and boundaries for indicating a find.
  • Character Classes: Specifies the specific kind of search (letters only, numbers only, etc.).
  • Groups and Backreferences/Lookarounds: Groups multiple patterns together. Lookarounds are used to refer to the previous or following groups of the same regex.
  • Quantifiers: Specifies the number of characters or patterns to find.

For the sake of brevity and simplicity we’ll only talk about Character Classes and how it relates to the question.

A Character Class’ purpose is to specify the type of character. Some notable Character Classes’ are:

  • []: Represents a list of types that a character could be. For example:

[a-zA-Z]: All letters upper or lower case

[/D/d]: Everything (All non-digits and digits)

  • [a-z]: Represents any character from a to z, though technically, you can replace the first character to any alphabetic letter as the starting point and the same with the second character but as the end point. Additionally /[A-Z]/ represents the same thing just with capital letters. Though please note that this does not detect symbols like "." or "?". For example:

[a-e]: All letters from a to e

[g-z]: All letters from g to z

[A-Eg-z]: All upper-case letters from a to e and all lower-case letters from g to z

  • [0-9]: Represents any number from 0 to 9, though technically, you can replace the first number to any other number as the starting point and the same with the second character but as the end point. For example:

[0-3]: All numbers from 0 to 3

[6-9]: All numbers from 6 to 9

  • \d: Represents all digits.
  • \D: Represents anything that isn’t a digit.
  • \w: Represents anything that’s a letter, including symbols.
  • \W: Represents anything that isn’t a letter, including symbols.
  • \s: Represents white space.
  • \S: Represents anything that isn’t white space.
  • [^...]: Represents anything that isn’t whatever is in the expression. Can contain all of the above. For example:

[^0-3/w]: Exclude all characters and numbers 0 to 3

[^/d/s]: Exclude all numbers and white space

You can make and learn regular expressions at the incredibly helpful and informative regexr.com.

Searching through Regex

To detect characters in JavaScript, you need to use the String class’ .search() and the RegExp class’ .test() function.

The .test() function works similar to the Array and String class’ .include() function, in that it will return true/false, but instead of looking for a substring it checks whether a regex pattern is found.

Similarly, the .search() is like the String class’ .indexOf() function as they both return the first index of an occurrence but .search() looks for a regex pattern instead of a character or substring. Though one thing of note is that .search() requires that you use === (strict equality) instead of == (regular equality) as 0 (first index) is technically false under regular equality.

Syntax:

String.prototype.search(regex);

Return: Returns the first index of the pattern, will return -1 if nothing is found

Parameters:

NameTypeDescription
regexRegular ExpressionThe regex used to search.

Example:

const str = "LearnShareIT";
console.log(str.search(/[a-z]/));

Output:

1

Syntax:

RegExp.prototype.test(str string);

Return: Returns true/false based on whether a regex is found in the string

Parameters:

NameTypeDescription
stringstringThe string to search in.

Example:

const str = "a123yet";
console.log(/[0-9]/.test(str));

Output:

true

As stated above, checking using the /[0-9]/ or /\d/ regex is absolutely not going to work, so you would need to use a regex that detects characters instead, so you might use something like the /[a-z]/ or /\D/ as shown below:

Code:

const fal_num = "123__";
const decimal = "23.145";
const num = "123";
const str = "abc123__";

function numTest(str) {
    if (!/[a-zA-Z]/.test(str)) console.log(`${str} Is A number`);
    else console.log(`${str} Is Not A number`);
    if (!/\D/.test(str)) console.log(`${str} Is A number`);
    else console.log(`${str} Is Not A number`);
}

numTest(str);
numTest(fal_num);
numTest(num);
numTest(decimal);

Output:

abc123__ Is Not A number
abc123__ Is Not A number
123__ Is A number
123__ Is Not A number
123 Is A number
123 Is A number
23.145 Is A number
23.145 Is Not A number

As you can see, there was an issue regarding fal_num, which contained some underscores ("_") and returned true when checking with the /[a-zA-Z]/ regex. Additionally, it recognizes the decimal (".") in the decimal variable and considers it not a number.

Therefore we have to use a different regex that both excludes the searching of both numbers and decimal symbols ("," or "."). To do this, instead of looking for all letters, we look for anything that isn’t a number or a decimal symbol by using the /[\d.,]/ regex instead. Lets try the same code again but with the new regex.

Code:

const fal_num = "123__";
const decimal = "23.145";
const num = "123";
const str = "abc123__";

function numTest(str) {
    if (!/[^\d.,]/.test(str)) console.log(`${str} Is A number`);
    else console.log(`${str} Is Not A number`);
}

numTest(str);
numTest(fal_num);
numTest(num);
numTest(decimal);

Output:

abc123__ Is Not A number
123__ Is Not A number
123 Is A number
23.145 Is A number

Summary

To check if string contains only digits in JavaScript, you need to check if a string contains anything that’s not a digit by using the /\D/ (or /[\d.,]/ regex if you are using decimal symbols). You can choose one of mentioned method in this article. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *