JavaScript Convert String to Integer
To convert a string to integer in JavaScript, call parseInt() function and pass the string as argument to it.
Optionally, we may pass the base/radix as second argument to parseInt() function.
parseInt() function returns an integer created from the given string and base/radix.
The syntax to convert a string str
to an integer is
parseInt(str)
The syntax to call parseInt() with base/radix is
parseInt(str, radix)
Examples
In the following example, we have taken a string in str
, and convert this string to integer using parseInt() function.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> </head> <body> <div id="output"></div> <script> var str = '325'; var x = parseInt(str); document.getElementById('output').innerHTML = 'Integer : ' + x; </script> </body> </html>
Now, let us give a base value of 8 and parse the integer from given string.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> </head> <body> <div id="output"></div> <script> var str = '325'; var radix = 8; var x = parseInt(str, radix); document.getElementById('output').innerHTML = 'Integer : ' + x; </script> </body> </html>
The returned value by parseInt() is a decimal value.
Conclusion
In this JavaScript Tutorial, we learned how to convert a string into integer using parseInt() function, with examples.