The parseInt() function takes at least one argument, the string from which to convert to an integer value. The script below uses parseInt() to extract an integer from a quoted floating point number.
var carter = "12.97";
alert( parseInt(carter).toString() );
The script above returned the number 12. It illustrates the parseInt() function's extracting logic: it does not attempt to round the extracted number the nearest integer. Instead, parseInt() makes the most of the string argument.
We will now pass more ambiguous arguments to the parseInt() function:
var carter1 = "13th is today's date";
var carter2 = "Today is the 13th";
alert( parseInt(carter1) +"\n"+ parseInt(carter2) );
Handling NaN Values Returned by the parseInt() Function
Whenever the parseInt() function is unsuccessful at converting a string to an integer value, it simply returns NaN ("Not a Number"). It is then easy to check on the success of the string to integer conversion before proceeding with your next code statement, by using the isNaN() function (covered later).
var userAge = "I am 13";
if( isNaN( parseInt(userAge) ) )
alert(" Please re-enter your age.");
The parseInt() function accepts a second, optional argument. The second argument determines in which base to express the integer extracted; if no second argument is passed, a conversion to base 10 occurs. The parseInt() function only performs a base conversion in case of successful extraction.
var numex = "F";
alert( parseInt(numex,16) );
The piece of code above extracted a base 16 (hexadecimal) number from a quoted letter "F" (case-insensitive), and returned 15, the value of F in base 16.
If the second argument had been omitted, or if 10 had been passed, the parseInt() function would have returned NaN.
Using regular expressions with parseInt()
// Declare a string containing an integer:
// Remove non-digits from the string we'll send to parseInt:
// (In other words, replace non-numbers with an empty string)
carter = carter.replace( /\D/g , "" );
// Parse integers in the resulting string:
var numex = parseInt(carter); // numex now contains integer value 5
parseInt( carter.replace(/\D/g,"") );
As you probably guessed, the symbol "
d" for digits, and escaped uppercase "
D" for non-digits). Whenever possible and feasible, you can use JS regular expressions to extend the integer-parsing abilities of the parseInt() function.
g" modifier in "
Test the parseInt() Function