How to Convert String to Int in JavaScript

To convert a String to int in JavaScript, you can use the “parseInt() function” or “Number object”.

Method 1: Using the parseInt() function

The parseInt() is a built-in function that parses a string argument and returns an integer of the specified radix. If the string contains any alphabet, it stops parsing at that moment or parses only integers before the alphabet.

Syntax

parseint(string, radix)

Arguments

string: It is the input value, which contains an integer and is to be converted.

radix: On the other side, specifies which number system is being used in terms of computer, For example, 2-Binary, 8=octal, etc., till 36.

Example 1

let x = '5helloworld';
console.log(parseInt(x)); 
let z = '111';
console.log(parseInt(z , 2));

Output

5
7

You can see that the parseInt() function has converted a 5helloworld” string into an integer value of 5.

Implementing radix = 2 takes all the input in binary digits like 111 and is converted into 7. By default, the numbers are converted into decimal values. 

Now a question might arise, what if we specify radix as 10 only. We can see that by taking another example.

Example 2

let data = '12';
console.log(parseInt(data, 10));

Output

12

Method 2: Using the Number object

The Number object in JavaScript converts any Boolean, dates, or string value into a number, or we can also say it converts them into integers. 

Syntax

Number (value);

Arguments

The Number() function accepts a value as an argument.

Example

Let’s convert string to int using the Number() function.

let data = "88"
console.log(Number(data));

Output

88

That’s it.

Leave a Comment