Member-only story
For more questions and answers visit our website at Frontend Interview Questions
1. Using parseInt()
The most commonly used method to convert a string to an integer in JavaScript is the parseInt()
function. This function parses a string argument and returns an integer of the specified radix (base).
Syntax:
parseInt(string, radix);
string
: The string to be converted.radix
: An optional parameter that defines the base of the numeral system (e.g., 10 for decimal, 16 for hexadecimal).
Example:
let str = "123";
let num = parseInt(str, 10);
console.log(num); // Output: 123
In this example, the string "123"
is converted into the integer 123
. The 10
represents the decimal numeral system. If you don't specify the radix, parseInt()
will try to infer it from the string, which could lead to unexpected results, especially with strings that start with 0
or 0x
.
Example with Radix:
let hexStr = "1a";
let num = parseInt(hexStr, 16); // Parse as hexadecimal
console.log(num); // Output: 26