$ snippet safe-parse-int

Safely parse a string to an integer

A toInt() helper that returns a fallback instead of NaN, rejects '12px' and '1e3', and never guesses the radix.

JavaScript
/**
 * Parse a string as a base-10 integer. Returns `fallback` for anything
 * that is not a clean integer ("12px", "1.5", "", null, "1e3").
 */
function toInt(value, fallback = null) {
  if (typeof value === "number") return Number.isInteger(value) ? value : fallback;
  if (typeof value !== "string") return fallback;
  const s = value.trim();
  if (!/^[+-]?\d+$/.test(s)) return fallback;
  const n = Number(s);
  return Number.isSafeInteger(n) ? n : fallback;
}

How it works

parseInt stops at the first non-digit, so parseInt("12px") is 12 and parseInt("1.9") is 1 — useful for CSS, dangerous for form input. Number() is stricter but turns "" and " " into 0 and accepts "1e3" and "0x1F". This helper validates the shape with a regex first, then converts, and checks the result fits in a safe integer.

Gotchas

Try it
Result
Ad slot