Node.JS/Javascript - casting string to integer is returning NaN when I wouldn't expect it to


This is all in the context of a larger program, so Im going to try keep it simple, showing the offending lines only. I have an array of values that are numbers in string form a la "84", "32", etc.

Yet THIS line

console.log(unsolved.length + " " + unsolved[0] + " " + parseInt(unsolved[0]) + " " + parseInt("84"));


4 "84" NaN 84

"84" is the array element Im trying to parseInt! Yet it won't work unless I take it out of the context of an array and have it explicitly written. What's going on?

6/20/2012 1:41:45 PM

Accepted Answer

You can try removing the quotations from the string to be processed using this function:

function stripAlphaChars(source) { 
  var out = source.replace(/[^0-9]/g, ''); 

  return out; 

Also you should explicitly specify that you want to parse a base 10 number:

parseInt(unsolved[0], 10);
6/20/2012 2:01:25 PM

parseInt would take everything from the start of its argument that looks like a number, and disregard the rest. In your case, the argument you're calling it with starts with ", so nothing looks like a number, and it tries to cast an empty string, which is really not a number.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow