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