Easy

isNumbersOnly

Prompt

Write a function isNumbersOnly that takes a string and returns true if it contains only numeric digits (0-9), and false otherwise. Empty strings, strings with spaces, and strings with any non-digit characters should return false.

Playground

Hint 1

You could loop through each character and check if it's a digit. In ASCII, the digits 0-9 have character codes 48 through 57. Use charCodeAt() to check each character.

Hint 2

Alternatively, a regular expression like /^\d+$/ matches strings that contain only digits from start to end. One line solution.

Solution

Explanation

Let's walk through the solution top to bottom, in the same order the code runs.

Empty string check

if (input === '') return false;

First, we handle the empty string. An empty string contains no digits, so it's not "numbers only." We return false right away without entering the loop.

Character-by-character check using ASCII codes

for (let i = 0; i < input.length; i++) {
const code = input.charCodeAt(i);
if (code < 48 || code > 57) {
return false;
}
}

Every character has an ASCII code. The digits 0 through 9 have consecutive codes: 48 ('0'), 49 ('1'), 50 ('2'), ... all the way to 57 ('9'). If a character's code falls outside that range, it's not a digit, and we return false.

This naturally catches everything that isn't a digit: letters ('a' is 97), symbols ('!' is 33), decimal points ('.' is 46), and spaces (' ' is 32). We don't need a separate check for any of these because they all fall outside the 48-57 range.

What about spaces?

You might wonder: don't we need a separate check for leading/trailing spaces like input.trim() !== input? No. A space character has ASCII code 32, which is less than 48. The loop catches it automatically. Whether the space is at the start, end, or middle of the string, the charCode check rejects it. No extra code needed.

Leading zeros

This approach also preserves leading zeros correctly. The string "01234" returns true because every character is a digit. If we had tried to convert the whole string to a number first (using Number() or parseInt()), "01234" would become 1234 and we'd lose the information that there was a leading zero.

If all checks pass

return true;

If we made it through every character without finding a non-digit, the string is numbers only.

Alternative: regex

You can solve this in one line with a regular expression:

function isNumbersOnly(input) {
return /^\d+$/.test(input);
}

^\d+$ means: start of string (^), one or more digits (\d+), end of string ($). If anything other than a digit exists in the string, or if the string is empty, it returns false. Both solutions are valid in an interview.