How to convert a string to an integer in JavaScript?
How do you convert a string into an integer in JavaScript? What are the methods available, and how do they handle different types of strings? Let’s explore the most effective ways to perform this conversion.
Converting a string to an integer in JavaScript is pretty straightforward, and you’ve got several options depending on what exactly you're trying to do. Here's how you can go about it:
1. Using parseInt()
This is the most commonly used method.
let num = parseInt("42"); // returns 42
- It parses a string and returns an integer.
- It stops parsing at the first non-digit character.
- You can also specify the radix (base), which is super helpful.
let binary = parseInt("1010", 2); // returns 10
2. Using Number()
This is a bit stricter than parseInt():
let num = Number("42"); // returns 42
let invalid = Number("42abc"); // returns NaN
- It tries to convert the whole string.
- Returns NaN if the string isn’t fully numeric.
3. Using Unary + Operator
A quick and clean way to convert:
let num = +"42"; // returns 42
- It’s very concise.
- But not very readable for beginners.
Things to Watch Out For:
- Leading/trailing spaces are usually fine, but mixed characters can break conversions.
- Always validate the result using isNaN() to avoid unexpected behavior.
Pro tip: Always sanitize user inputs before conversion to avoid bugs or unexpected values.