Convert Integer To Its Character Equivalent In JavaScript

Convert Integer to its Character Equivalent in JavaScript

During JavaScript web application development, we may get a requirement to convert integer to its character equivalent. This article will share how to use the recursive functions and fromCharCode() to do it. Let’s read it now.

How to convert integer to its character equivalent in JavaScript

To convert integer to its character equivalent, we have the following two solutions:

  • Using the recursive functions
  • Using the fromCharCode() method

Now, we will take a closer look at each solution with specific examples for each of them.

Using the recursive functions

We have a string literal ‘abcdefghijklmnopqrstuvwxyz’. To get the character equivalent to an integer (less than 26), we need to get the character at the index, which is the integer already present.

Example:

// Convert integer to its character equivalent
function eqChar(i) {
   return 'abcdefghijklmnopqrstuvwxyz' [i];
}

console.log(eqChar(11));

Output:

l

We will use a recursive function if the integer is greater than 25.

The eqChar() recursive function will return the empty string if i < 26 and recursively if i >= 26 with the new parameter i = Math.floor(i / 26) - 1, then return the character at index [i % 26] of the string ‘abcdefghijklmnopqrstuvwxyz’.

The Math.floor() method rounds down and returns an integer less than or equal to the specified value.

Example:

// Convert integer to its character equivalent
function eqChar(i) {
   return (
      (i >= 26 ? eqChar(Math.floor(i / 26) - 1) : '') +
      'abcdefghijklmnopqrstuvwxyz' [i % 26]
   );
}

console.log(eqChar(5572749), eqChar(8824300), eqChar(253));

Output:

learn share it

Using the fromCharCode() method

The String.fromCharCode() method returns a string generated from an integer representing the UTF-16 code.

Syntax:

String.fromCharCode(num1, …, numN)

Parameter:

  • num1, …, numN: integers representing the UTF-16 code (between 0 and 65535).

In UTF-16, the character ‘a’ has an index of 97, and the character ‘A’ has an index of 65.

Suppose in the alphabet, we set the index of ‘a’ to be 0, then when we use the fromCharCode() method to convert integer to its equivalent character, we have to increment that integer by 97 (65 for ‘A’).

Example:

// Convert integer to its character equivalent
function eqChar(i) {
   return String.fromCharCode(97 + i, 65 + i);
}

console.log(eqChar(11));

Output:

lL

If you need to get the alphabet’s characters, make sure i < 26.

Summary

This article has shown how to convert integer to its character equivalent in JavaScript. I hope the information in this article will be helpful to you. If you have any problems, please comment below. I will answer. Thank you for reading!

Maybe you are interested:

Leave a Reply

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