const tempstr = 'This is an example string';
function stringBreakers(n, string) {
string = string.replace(/\s/g, '');
let resultStr = '';
for (let i = 0; i < string.length; i += n) {
resultStr += string.slice(i, i + n);
if (i + n < string.length) resultStr += '\n';
}
return resultStr;
}
stringBreakers(5, tempstr);
function stringBreakers(n, string){
let result = '';
let counter = 0;
for (const letter of string) {
if (letter === ' ') continue;
if (counter === n) {
result += '\n';
counter = 0;
}
result += letter
++counter;
}
return result;
}
stringBreakers(5, tempstr);
function stringBreakers(n, string) {
const parts = [];
const str = string.replace(/\s/g, '');
const breakString = (s) => {
const firstPart = s.slice(0, n);
const secondPart = s.slice(n, string.length);
parts.push(firstPart);
if (secondPart.length > n) {
breakString(secondPart);
} else {
parts.push(secondPart);
}
}
breakString(str);
return parts.join('\n');
}
stringBreakers(5, tempstr);
function stringBreakers(n, string) {
let arr = string.replace(/\s+/g, '').split('');
for (let i = 1; i * (n + 1) <= arr.length; i++) {
arr.splice(i * (n + 1) - 1, 0, '\n');
}
return arr.join('');
}
stringBreakers(5, tempstr);
function stringBreakers(n, s){
return s.replace(/\s/g,'').replace(new RegExp('.{'+n+'}','g'),'$&\n').trim()
}
stringBreakers(5, tempstr);