How to split a string into chunks of two characters each using RegEx in JavaScript

1 Answer

0 votes
function splitStringIntoChunksUsingRegex(str, chunkSize) {
    // Match groups of `chunkSize` characters
    const regex = new RegExp(`.{1,${chunkSize}}`, 'g');
    
    return str.match(regex);
}


const str = "abcdefghijk";
const chunkSize = 2;
const chunks = splitStringIntoChunksUsingRegex(str, chunkSize);

console.log("Chunks of two characters:");
chunks.forEach(chunk => console.log(chunk));


   
/*
run:
    
Chunks of two characters:
ab
cd
ef
gh
ij
k
       
*/

 



answered Mar 30, 2025 by avibootz
...