Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript split the number into separate two char digits

I am trying to solve a math problem where I take a number e.g. 45256598 % 2==0 and then split the number into separate two char digits like e.g. 45,25,65,98. Does anyone know how to split a number into individual two char digits?
I Have Already Achieved this C# code but this Method I am looking in JavaScript code :-

My C# code is:-

string str = "45256598";
        int n = 2;
IEnumerable<string> numbers = Enumerable.Range(0, str.Length / n).Select(i => str.Substring(i * n, n));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

<!DOCTYPE html>
<html>
<body>
    <script>
        const str = "45256598";
        if((str * 1) % 2 === 0) {
            const numArr = [];
            for(let i = 0; i < str.length; i = i + 2) {
                const twoDigit = str.charAt(i) + (str.charAt(i+1) ?? ''); // To handle odd digits number
                numArr.push(twoDigit);
            }
            let result = numArr.join(',');
            console.log(result);
        }
    </script>
</body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading