0

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));
David Thomas
  • 249,100
  • 51
  • 377
  • 410
Pankaj
  • 25
  • 4
  • 1
    What is the significance of doing the `% 2`? Do you only want to split your string if it's divisible by 2 (your C# doesn't seem to do that)? Is your number also a string to begin with like it is in your C# code? – Nick Parsons Sep 26 '22 at 11:13
  • Is this what you're after? [Split large string in n-size chunks in JavaScript](https://stackoverflow.com/q/7033639) – Nick Parsons Sep 26 '22 at 11:15
  • `[...'45256598'.matchAll(/../g)].map(m => m[0]).join(',')` – Keith Sep 26 '22 at 11:17
  • Thanks Nick for your Help. Now Problem Solved – Pankaj Sep 26 '22 at 11:28

2 Answers2

2

You can do this by using match

like this:

const splittedNumbers = "45256598".match(/.{1,2}/g)

This will return array of:

['45','25','65','98']

If you would like to split in different length, just replace 2 with the length

const splittedNumbers = "45256598".match(/.{1,n}/g)

Hope this will help you!

SWIK
  • 714
  • 7
  • 12
0

<!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>
sasi66
  • 437
  • 2
  • 7