how to convert string to int js
How to Convert String to Int in JavaScript
If you have a string variable in JavaScript and you want to convert it into an integer, there are several ways to do it. Let's take a look at some of the most common methods:
Method 1: parseInt()
The parseInt() function is used to convert a string to an integer in JavaScript. Here's how it works:
let str = "123";
let num = parseInt(str);
console.log(num); // Output: 123
Method 2: Number()
The Number() function is another way to convert a string to an integer in JavaScript:
let str = "123";
let num = Number(str);
console.log(num); // Output: 123
Method 3: Unary Plus Operator
You can also use the unary plus operator (+) to convert a string to an integer:
let str = "123";
let num = +str;
console.log(num); // Output: 123
Method 4: Using the Bitwise Operator
Another way to convert a string to an integer is by using the bitwise operator. This method is not recommended as it is not very efficient and can cause unexpected results for large numbers:
let str = "123";
let num = ~~str;
console.log(num); // Output: 123
So, these are some of the most common ways to convert a string to an integer in JavaScript. You can choose the method that suits your needs the best.