In JavaScript, you can convert a string to an integer using the following methods:

1. Using parseInt():

let str = "123";
let num = parseInt(str);
console.log(num); // 123

2. Using the unary plus (+) operator:

let str = "123";
let num = +str;
console.log(num); // 123

3. Using Number():

let str = "123";
let num = Number(str);
console.log(num); // 123

Notes:

  • parseInt() will ignore non-numeric characters after a valid number, so “123abc” will be converted to 123.
  • If the string cannot be converted to a valid number (e.g., “abc”), parseInt(), +, and Number() will return NaN (Not-a-Number). You can handle this by checking isNaN():
let str = "abc";
let num = parseInt(str);
if (isNaN(num)) {
    console.log("Not a valid number!");
}

Need Help With Javascript Development?

Work with our skilled Javascript developers to accelerate your project and boost its performance.

Hire JavaScript Developers

Support On Demand!

Related Q&A