JavaScript: Convert String to Integer (int)

To convert strings (text) to integer (number) in JavaScript use the parseInt function.

For example:

document.write(parseInt("23 years"));

Will return the number 23, the function ignores the string “years” and return the integer 23 only.

Another common example is:





 

If you enter 4 and 5, the script will return “45”  instead of 9.  To fix use the parseInt function as follows:






 

 

Leave a Reply

Your email address will not be published. Required fields are marked *