Skip to content
the poor coder

how to convert string to int js

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

    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:

Text

    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:

Text

    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:

Text

    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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC