To convert a string to int in JavaScript, you can use the “parseInt()”, “unary plus operator (+)”, or “Number()” method.
Method 1: Using the parseInt() method
The easiest way to convert a string to an integer in JavaScript is to use the “parseInt()” method. The parseInt() function is “used to return NaN, which means not a number when the string doesn’t hold a number”.
Syntax
parseInt(value, radix);
Parameters
- value: It takes a value as a string and converts it into an integer.
- radix: It is used to define which numeral system to be used. For example, a radix of 16 (hexadecimal) indicates that a number in the string should be parsed from the hexadecimal Number to the decimal Number.
Return Value
It returns the integer value that is parsed from the string.
Example
let a = parseInt("11")
let b = parseInt("11.00")
let c = parseInt("11.21")
let d = parseInt("11 21 29")
let e = parseInt(" 19 ")
let f = parseInt("18 years")
let g = parseInt("He was 40")
console.log(a, typeof (a))
console.log(b, typeof (b))
console.log(c, typeof (c))
console.log(d, typeof (d))
console.log(e, typeof (e))
console.log(f, typeof (f))
console.log(g, typeof (g))
Output
11 number
11 number
11 number
11 number
19 number
18 number
NaN number
In this example, various cases of strings, such as only strings, strings within, and integers, have been taken and sent through a parseInt() method.
Method 2: Using the unary plus(+) operator
The unary plus operator (+) is a single operand operator that converts its operand to a number if it isn’t already a number. It can convert string representations of integers and floats, as well as true, false, and null.
Syntax
+operator
Example
let x = +"20"; // x is 20
let y = +true; // y is 1
let z = +null;
console.log(typeof(x))
console.log(typeof(y))
console.log(typeof(z))
Output
number
number
number
Method 3: Using the Number() method
JavaScript Number() is a built-in method that converts a string to an integer, but sometimes it’s an integer, and other times it’s the point number. So if you pass in the string with random text, you will get NaN in the output.
Syntax
Number(value)
Parameters
The Number() method takes a value as a parameter, which is a string.
Return Value
The Number() method returns the integer value of a string.
Example
let a = Number("11")
let b = Number("11.00")
let c = Number("11.21")
let d = Number("11 21 29")
let e = Number(" 19 ")
let f = Number("18 years")
let g = Number("He was 40")
console.log(a, typeof (a))
console.log(b, typeof (b))
console.log(c, typeof (c))
console.log(d, typeof (d))
console.log(e, typeof (e))
console.log(f, typeof (f))
console.log(g, typeof (g))
Output
11 number
11 number
11.21 number
NaN number
19 number
NaN number
NaN number
That’s it.