$ 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.
/**
* 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
parseInt("08")used to return 0 in old engines (octal). Always pass a radix if you useparseIntdirectly:parseInt(s, 10).Number.isInteger(1e21)is true but the value is aboveNumber.MAX_SAFE_INTEGER— henceisSafeInteger.- If you actually want to read a leading number from "12px",
parseInt(s, 10)is the right tool; this helper is for validation.
Ad slot