How to split string into substrings of N characters in Node.js

1 Answer

0 votes
function splitStrings(str, n) {
  	const arr = [];

  	for (let i = 0; i < str.length; i += n) {
    		arr.push(str.slice(i, i + n));
  	}

  	return arr;
}

const str = 'javascript c++ c typescript php node.js';
const N = 4;

console.log(splitStrings(str, N));

  
  
  
  
/*
run:
  
[
  'java', 'scri',
  'pt c', '++ c',
  ' typ', 'escr',
  'ipt ', 'php ',
  'node', '.js'
]
  
*/

 



answered Apr 15, 2022 by avibootz
...