How to split a string into chunks of two characters each using RegEx in Node.js

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 hi";
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 
hi
       
*/

 



answered Mar 31 by avibootz
...