Wednesday, September 3, 2025
HomeLanguagesJavascriptSplit a number into individual digits using JavaScript

Split a number into individual digits using JavaScript

In this article, we will get some input from user by using <input> element and the task is to split the given number into the individual digits with the help of JavaScript. There two approaches that are discussed below:

Approach 1: First take the element from input element in string format (No need to convert it to Number) and declare an empty array(var res). Visit every character of the string in a loop on the length of the string and push the character in the array(res) by using push() method

Example: This example implements the above approach. 

Javascript




function GFG_Fun() {
    let str = "123456";
 
    let res = [];
 
    for (let i = 0, len = str.length; i < len; i += 1) {
        res.push(+str.charAt(i));
    }
 
    console.log(res);
}
 
GFG_Fun();


Output

[ 1, 2, 3, 4, 5, 6 ]

Approach 2: First take the element from input element in string format (No need to convert it to Number) and declare an empty array(var res). Split the string by using split() method on (”) and store the splitted result in the array(str). 

Example: This example implements the above approach. 

Javascript




function GFG_Fun() {
    let n = "123456";
    let str = n.split('');
    console.log(str);
}
 
GFG_Fun();


Output

[ '1', '2', '3', '4', '5', '6' ]
RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6746 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS