Better solutions of spliting a string?

I have a function that split a given 16 digits into 4 groups of 4 digits each with space between each group (ie. AAAABBBBCCCCDDDD β†’ AAAA BBBB CCCC DDDD

I use the follow way to split the string but is there a more elegant way of doing it?

let confirmNo1 = confirmNo.toString().substring(0,4);
let confirmNo2 = confirmNo.toString().substring(4,8);
let confirmNo3 = confirmNo.toString().substring(8,12);
let confirmNo4 = confirmNo.toString().substring(12,16);

Below is how I display the split strings in the react code.

<div className="confirmNo">
    {confirmNo1 + " " + confirmNo2 + " " + confirmNo3 + " " + confirmNo4}
</div>

you can also use for loop in combination with slice method to get result

for(let i=0; i<str.length;i+=groupCount)
    ans+=str.slice(i,i+groupCount)+' '

0.166ms with your input

you can also use regex for the same but since it’s pattern based it will take more time

let re = /\w{4}/g
return x.match(re).join(' ')

default: 10.999ms

2 Likes

You can use the split() method to turn the original string into an array of substrings and then the join() method to turn it back into a single string.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.