Converting a string to an integer in JavaScript is surprisingly subtle because parseInt() stops at trailing characters like "42px" and Number() converts "" or whitespace into 0. For strict parsing, validate the input first and use Number.parseInt(str, 10)—or Number() / BigInt() depending on whether you allow decimals, whitespace, or integers beyond Number.MAX_SAFE_INTEGER.
1. Strict Integer Parsing Helper (Number.parseInt + Validation)
Always pass base 10 as the second argument to Number.parseInt() and verify the string actually represents an integer so "42abc" or "" does not slip through silently:
function parseStrictInt(value) {
if (typeof value !== "string") return null;
const trimmed = value.trim();
if (!/^[+-]?\d+$/.test(trimmed)) return null;
const parsed = Number.parseInt(trimmed, 10);
return Number.isSafeInteger(parsed) ? parsed : null;
}
console.log(parseStrictInt("128")); // 128
console.log(parseStrictInt(" -42 ")); // -42
console.log(parseStrictInt("42px")); // null (rejected instead of returning 42)
console.log(parseStrictInt("")); // null (rejected instead of returning 0)
2. Choosing Between Number.parseInt(), Number(), and BigInt()
Number.parseInt(str, 10): Reads leading integer digits in base 10, but ignores trailing non-digits ("100%"->100) and treats1e3differently than"1000".Number(str)+Number.isInteger(): Converts the whole trimmed string (Number("")is0,Number("12.5")is12.5,Number("12px")isNaN), makingNumber.isInteger()useful only after checking for non-empty strings.BigInt(str): Use when values can exceedNumber.MAX_SAFE_INTEGER(9007199254740991), such as 64-bit database IDs or snowflake IDs.
3. Common Traps to Avoid
- Omitting the radix (
10) inparseInt(): Always specify10so base expectations are explicit and easy to read. - Letting
parseInt()silently accept partial strings: Form inputs like"15 items"or"12.99"should usually fail validation or be handled intentionally rather than silently parsed as15or12. - Ignoring
Number.isSafeInteger(): Above9007199254740991, standard IEEE-754 JavaScript numbers lose precision on integer increments and comparisons.
TL;DR: Validate the trimmed string against /^[+-]?\d+$/, convert with Number.parseInt(trimmed, 10), check Number.isSafeInteger() for standard integers, and use BigInt() if values can exceed Number.MAX_SAFE_INTEGER.
Are you parsing user form inputs, numeric IDs (including potentially large 64-bit IDs), or strings that might include signs or decimals?
