0
0
JavascriptHow-ToBeginner · 2 min read

JavaScript How to Convert String to Integer Easily

You can convert a string to an integer in JavaScript using parseInt(string) or Number(string), for example: parseInt('123') returns 123.
📋

Examples

Input'123'
Output123
Input'42abc'
Output42
Input'abc123'
OutputNaN
🧠

How to Think About It

To convert a string to an integer, think about extracting the number part from the string. Use parseInt to read the number from the start of the string until it hits a non-digit. If the string starts with digits, it returns those as a number; otherwise, it returns NaN. Alternatively, Number tries to convert the whole string strictly to a number.
📐

Algorithm

1
Take the input string.
2
Use a function that reads the string and extracts the integer value.
3
If the string starts with digits, convert those digits to an integer.
4
If the string does not start with digits, return NaN.
5
Return the integer value.
💻

Code

javascript
const str1 = '123';
const str2 = '42abc';
const str3 = 'abc123';

console.log(parseInt(str1)); // 123
console.log(parseInt(str2)); // 42
console.log(parseInt(str3)); // NaN
Output
123 42 NaN
🔍

Dry Run

Let's trace '42abc' through the code

1

Input string

'42abc'

2

Apply parseInt

Reads '42' as number, stops at 'a'

3

Return result

42 as integer

StepString ReadResult
1'42abc'N/A
2'42'42
3N/A42
💡

Why This Works

Step 1: parseInt reads from the start

The parseInt function reads the string from the beginning and converts digits until it finds a non-digit.

Step 2: Stops at first non-digit

When parseInt encounters a non-digit character, it stops reading and returns the number parsed so far.

Step 3: Returns NaN if no digits at start

If the string does not start with digits, parseInt returns NaN to indicate conversion failure.

🔄

Alternative Approaches

Number() function
javascript
const str = '123';
console.log(Number(str)); // 123
Converts the whole string strictly; returns NaN if any non-digit characters exist.
Unary plus operator
javascript
const str = '123';
console.log(+str); // 123
A shorthand to convert string to number; behaves like Number() and returns NaN if invalid.

Complexity: O(n) time, O(1) space

Time Complexity

Conversion functions scan the string once, so time grows linearly with string length.

Space Complexity

No extra memory is needed besides a few variables, so space is constant.

Which Approach is Fastest?

parseInt, Number, and unary plus all run in similar time; choose based on input format.

ApproachTimeSpaceBest For
parseIntO(n)O(1)Strings with numbers followed by text
NumberO(n)O(1)Strict numeric strings only
Unary plusO(n)O(1)Quick conversion of clean numeric strings
💡
Use parseInt when the string may have extra characters after the number.
⚠️
Trying to convert strings with letters using Number() without handling NaN results.