How to split a string into fixed length chunks in JavaScript

1 Answer

0 votes
function splitStringIntoChunks(str, length) {
    const regex = new RegExp(`.{1,${length}}`, 'g');
    
    return str.match(regex);
}

const inputString = "javascript c++ c python c#";
const chunkLength = 5;

const chunks = splitStringIntoChunks(inputString, chunkLength);

console.log(chunks);



/*
run:

[ 'javas', 'cript', ' c++ ', 'c pyt', 'hon c', '#' ]

*/

 



answered Jul 24, 2024 by avibootz

Related questions

1 answer 139 views
1 answer 135 views
1 answer 123 views
1 answer 136 views
1 answer 164 views
1 answer 146 views
2 answers 211 views
...