Prem
Prem

Reputation: 5987

How does parseInt() in Javascript work?

    console.log(parseInt('01abbb')) // 1
    console.log(parseInt('31xyz'))  // 31
    console.log(parseInt('zyz31'))  // NaN
    console.log(parseInt('31xyz1')) // 31

Does parseInt() ignore the suffix from the index where the character happens not to be an integer?

Upvotes: 0

Views: 708

Answers (4)

Isaac
Isaac

Reputation: 12874

For more information please refer to documentation

Note: Only the first number in the string is returned!

Note: Leading and trailing spaces are allowed.

Note: If the first character cannot be converted to a number, parseInt() returns NaN.

Note: Older browsers will result parseInt("010") as 8, because older versions of ECMAScript, (older than ECMAScript 5, uses the octal radix (8) as default when the string begins with "0". As of ECMAScript 5, the default is the decimal radix (10).

Upvotes: 1

Carcigenicate
Carcigenicate

Reputation: 45736

From Microsoft's docs:

If no prefix of numString can be successfully parsed into an integer, NaN(not a number) is returned.

So yes, only parsable prefixes are returned.

Upvotes: 1

Kolt Penny
Kolt Penny

Reputation: 164

ParseInt reads until it stops seeing a number. Since xyz is not a number, it returns NaN (Not a Number).

Upvotes: 1

Afshin
Afshin

Reputation: 9173

You only get number till where it is meaningful when converting from string to number.

console.log(parseInt('01abbb')) // 1 -> it is started by 01 before chars
console.log(parseInt('31xyz'))  // 31 -> it is started by 31 before chars
console.log(parseInt('zyz31'))  // NaN -> it is not started by numbers
console.log(parseInt('31xyz1')) // 31 -> it is started by 31 before chars

Upvotes: 2

Related Questions