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));
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? Commented Sep 26, 2022 at 11:13
  • Is this what you're after? Split large string in n-size chunks in JavaScript Commented Sep 26, 2022 at 11:15
  • [...'45256598'.matchAll(/../g)].map(m => m[0]).join(',') Commented Sep 26, 2022 at 11:17
  • Thanks Nick for your Help. Now Problem Solved Commented Sep 26, 2022 at 11:28

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.