Exercise 13: Check if String Contains Only Digits

Problem Statement

Create a function `isNumeric(str)` that checks if string contains only digits. Example: - isNumeric("123") → true - isNumeric("12a") → false

Sample Output:

isNumeric("123") => true
isNumeric("12a") => false
isNumeric("") => false

Solution

const isNumeric = (str) => {
  const s = String(str ?? "");
  return s.length > 0 && /^\d+$/.test(s);
};

Explanation

Overall Goal:

  • String me sirf digits hain ya nahi check karna.

Line 1: Function header

  • const isNumeric = (str) => {

Line 2: Convert

  • const s = String(str ?? "");

Line 3: Regex test

  • return s.length > 0 && /^\d+$/.test(s);
  • ^\d+$ → start se end tak sirf digits.

Real world:

  • Form validation: numeric inputs.
  • Data validation: number strings.