parseIntDef()
parseIntDef(
value,defaultValue,radix?):number|null
Parses a string to an integer with a fallback default value.
remarque
Returns default for null, undefined, empty strings, and NaN results.
Parameters
value: Nullish<string>
The string value to parse (can be nullish or empty).
defaultValue: Nullish<number> = null
The value to return if parsing fails.
radix?: number
The radix (base 2-36) for parsing.
Returns: number | null
The parsed integer or default value.
See Also
Since
1.0.0
Example
parseIntDef('42'); // => 42
parseIntDef('invalid'); // => null
parseIntDef('invalid', 0); // => 0
parseIntDef('1010', null, 2); // => 10 (binary)
parseIntDef('FF', null, 16); // => 255 (hex)
How it works?
Parses a string to an integer with a fallback default value, supporting custom radix.
Validation Flow
Common Inputs
| Value | Default | Radix | Result |
|---|---|---|---|
'42' | null | - | 42 |
'invalid' | 0 | - | 0 |
'1010' | null | 2 | 10 |
'FF' | null | 16 | 255 |
null | 0 | - | 0 |
Use Cases
Parse integers safely 📌
Convert strings to integers with nullish handling and default values. Essential for pagination (page numbers, limits) and ID handling.
const page = parseIntDef(params.page, 1);
const limit = parseIntDef(params.limit, 20);
Specify radix explicitly
Parse binary, octal, or hexadecimal strings safely. Useful for low-level data processing or color parsing.
const flags = parseIntDef("1010", 0, 2); // Binary to decimal: 10
const color = parseIntDef("FF", 0, 16); // Hex to decimal: 255