parseIntDef()
parseIntDef(
value,defaultValue?,radix?):number|null
Parses a string to an integer with a fallback default value.
note
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