Zhihar
Zhihar

Reputation: 1428

Parse an integer (and *only* an integer) in JavaScript

Prompt as it is possible to translate a string to number so that only any variant except for the integer produced an error.

func('17') = 17;
func('17.25') = NaN
func(' 17') = NaN
func('17test') = NaN
func('') = NaN
func('1e2') = NaN
func('0x12') = NaN

ParseInt does not work, because it does not work correctly.

ParseInt('17') = 17;
ParseInt('17.25') = 17 // incorrect
ParseInt(' 17') = NaN
ParseInt('17test') = 17 // incorrect
ParseInt('') = NaN
ParseInt('1e2') = 1 // incorrect

And most importantly: for the function to work in IE, Chrome and other browsers!!!

Upvotes: 12

Views: 2456

Answers (2)

gyre
gyre

Reputation: 16777

You can use a regular expression and the ternary operator to reject all strings containing non-digits:

function intOrNaN (x) {
  return /^\d+$/.test(x) ? +x : NaN
}

console.log([
  '17', //=> 17
  '17.25', //=> NaN
  ' 17', //=> NaN
  '17test', //=> NaN
  '', //=> NaN
  '1e2', //=> NaN
  '0x12' //=> NaN
].map(intOrNaN))

Upvotes: 14

Linus Thiel
Linus Thiel

Reputation: 39223

This would satisfy all your tests:

function func (str) {
  var int = parseInt(str, 10);
  return str == str.trim() && str == int ? int : NaN
}

Upvotes: 3

Related Questions