Open In App
Related Articles

How to convert string of any base to an integer in JavaScript ?

Improve Article
Save Article
Like Article

Given a string containing an integer value and along with that user passes a base value. We need to convert that string of any base value to an integer in JavaScript.

String          Integer
"1002"            1002

For performing the above-illustrated task, we would be using a method (or a function) provided by JavaScript called as parseInt(). 

This is a special method, provided by JavaScript, that takes an integer value (of any base which is either specified or not) and further converts the string into an integer value.


  • Following is the syntax that a user may use to convert a string into an integer value (of any base)-

    parseInt(string_value, base)
  • Alternatively, if we don’t want to specify the base value and just want to convert our string value into an integer value itself, then we may use the following syntax also-


Default value returned by base or radix of parseInt() method is 10. In other words, if we don’t specify any base or radix value then it by default converts the string value to an integer value by taking into regard the base or radix value as 10.

Let us visualize all of the above-illustrated facts with some of the following examples-

Example 1: In this example, we would be passing the string value in a method (which is explicitly declared for ease purpose) and further that string value is passed inside the parseInt() method which then further converts that string value in the corresponding integer value.


    let stringConversion = (string_value) => {
      console.log("Initial Type: " + typeof string_value);
      let integer_value = parseInt(string_value);
      console.log("Final Type: " + typeof integer_value);


Initial Type: string
Final Type: number
Initial Type: string
Final Type: number
Initial Type: string
Final Type: number

Example 2: In this example, we would be passing the base value explicitly inside the method which is then further taken by the parseInt() method and further converts the string value into the corresponding integer value by taking into account the specified base value also.


    let StringConversion = (string_value, base) => {
        "String value is : " + string_value + 
        " and base value is: " + base
      let Integer_value = parseInt(string_value, base);
      console.log("Integer value is: " + Integer_value);
    StringConversion("1011", 2);
    StringConversion("101", 10);
    StringConversion("10002", 8);


String value is : 1011 and base value is: 2
Integer value is: 11
String value is : 101 and base value is: 10
Integer value is: 101
String value is : 10002 and base value is: 8
Integer value is: 4098

Last Updated : 12 Jan, 2022
Like Article
Save Article
Similar Reads
Related Tutorials