Convert integer parseInt() method in Javascript
A parseInt() method used to convert string to number which allows space in the string. It allows space but string must starts with either space or number.
Syntax
 1 parseInt(<value>)
value : An integer value string that may contain space or characters

Valid conversion

Valid conversion
 1 // valid conversion
 2 // convert from number
 3 let res1 = parseInt("100"); // returns 100
 4 console.log(res1);
 5 
 6 // convert with space
 7 let res2 = parseInt("  120  "); // returns 100
 8 console.log(res2);
 9 
 10 // convert with number and string number
 11 let res3 = parseInt("140 number "); // returns 100
 12 console.log(res3);
In the above examples, a parseInt() function is called by passing a number in string data type and with leading and trailing white space that converts number values. If specified value ends with string number which is also a valid number. It converts a number and assigned to the variable and print.
Output
 1 100
 2 120
 3 140

Invalid conversion

Invalid conversion
 1 // invalid conversion
 2 
 3 // invalid conversion with leading string as nubmer
 4 let res1 = parseInt("number 100"); // return NaN
 5 console.log(res1);
 6 
 7 // invalid conversion with empty string
 8 let res2 = parseInt(""); // return NaN
 9 console.log(res2);
In the above example, a parseInt() is called by passing a string that starts with string number and number value and calls constructor with empty string which will return NAN that assigned to the variable and print.
Output
 1 NaN
 2 NaN
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us