Get the second digit of a number in JavaScript
In this tutorial, we will learn how to get the second of a number in JavaScript.
Getting the second digit of a number
To access the second digit of a number:
-
Convert the number to a string.
-
Call the
charAt()
method on it, by passing the second digit index1
. -
It returns the character at that index.
Here is an example:
const id = 13456;
const secondDigit = String(id).charAt(1);
// converting string back to number
console.log(Number(secondDigit));
Output:
3
The charAt() method accepts the character index as an argument and return its value in the string.
Similarly, we can also use the square brackets notation []
in JavaScript to get the second digit of a number.
Here is an example:
const id = 13456;
const secondDigit = String(id)[1];
// converting string back to number
console.log(Number(secondDigit));
Output:
3