How to split a string into fixed length chunks in TypeScript

1 Answer

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

const inputString: string = "typescript c++ c python c#";
const chunkLength: number = 5;

const chunks = splitStringIntoChunks(inputString, chunkLength);

console.log(chunks);



/*
run:

["types", "cript", " c++ ", "c pyt", "hon c", "#"] 

*/

 



answered Jul 24, 2024 by avibootz

Related questions

1 answer 122 views
1 answer 113 views
1 answer 107 views
1 answer 120 views
1 answer 150 views
1 answer 129 views
2 answers 194 views
...