To convert a string to an integer parseInt() function is used in javascript. parseInt() function returns Nan( not a number) when the string doesn’t contain number. If a string with a number is sent then only that number will be returned as the output. This function won't accept spaces. If any particular number with spaces is sent then the part of the number that presents before space will be returned as the output.
syntax
parseInt(value);
This function takes a string and converts it into an integer. If there is no integer present in the string, NaN will be the output.
Example
In the following example, various cases of strings such as only strings, strings with numbers, etc have been taken and sent through the parseInt() function. Later on, their integer values, if present, have displayed as shown in the output.
<html> <body> <script> var a = "10"; var b = parseInt(a); document.write("value is " + b); var c = parseInt("423-0-567"); document.write("</br>"); document.write('value is ' + c); document.write("</br>"); var d = "string"; var e = parseInt(d); document.write("value is " + e); document.write("</br>"); var f = parseInt("2string"); document.write("value is " + f); </script> </body> </html>
Output
value is 10 value is 423 value is NaN value is 2