How can I convert a string to a number with a specific base in JavaScript?
Davide S
davide s profile pic

In JavaScript, you can convert a string to a number with a specific base using theparseInt() function. TheparseInt() function takes two arguments: the string to convert and the base to use for the conversion. Here's how you can do it:

1
2
3
4

const stringToConvert = '101010';
const base = 2;
const convertedNumber = parseInt(stringToConvert, base);

In this example,stringToConvert holds the string you want to convert, which is'101010'.base represents the base of the number system you want to use for the conversion, which is2 for binary in this case. TheparseInt() function takes these two arguments and converts the string to a number using the specified base. The result is stored in theconvertedNumber variable. It's important to note thatparseInt() assumes a base-10 conversion by default. However, by providing thebase argument, you can specify a different base for the conversion, ranging from2 to36. The base determines the valid digits for the number and the positional value of each digit. For example, if you want to convert a string to a hexadecimal number, you can use a base of16:

1
2
3
4

const stringToConvert = 'FF';
const base = 16;
const convertedNumber = parseInt(stringToConvert, base);

In this case, thestringToConvert is'FF', representing the hexadecimal value. By specifyingbase as16, theparseInt() function converts the string to the corresponding decimal number. It's worth noting thatparseInt() returns a number in base-10 format regardless of the specified base. If you need to represent the number in a specific base, you can useNumber.toString() orNumber.toString(base) to convert the number back to a string in the desired base.

1
2
3
4

const number = 42;
const base = 16;
const stringInBase = number.toString(base);

In this example,number.toString(base) converts the decimal42 to the corresponding hexadecimal string'2A'. Ensure that the string and the base align correctly. If the string contains invalid characters for the specified base,parseInt() will returnNaN (Not a Number). Also, consider the range limitations of the number representation in JavaScript, particularly for large numbers in bases other than 10.