xxxxxxxxxx
// Static Width (Plain Regex)
const wrap = (s) => s.replace(
/(?![^\n]{1,32}$)([^\n]{1,32})\s/g, '$1\n'
);
// Dynamic Width (Build Regex)
const wrap = (s, w) => s.replace(
new RegExp(`(?![^\\n]{1,${w}}$)([^\\n]{1,${w}})\\s`, 'g'), '$1\n'
);
xxxxxxxxxx
function breakTextNicely(text, limit, breakpoints) {
var parts = text.split(' ');
var lines = [];
text = parts[0];
parts.shift();
while (parts.length > 0) {
var newText = `${text} ${parts[0]}`;
if (newText.length > limit) {
lines.push(`${text}\n`);
breakpoints--;
if (breakpoints === 0) {
lines.push(parts.join(' '));
break;
} else {
text = parts[0];
}
} else {
text = newText;
}
parts.shift();
}
if (lines.length === 0) {
return text;
} else {
return lines.join('');
}
}
var mytext = 'this is my long text that you can break into multiple line sizes';
console.log( breakTextNicely(mytext, 20, 3) );
xxxxxxxxxx
var protest = "France is actually the worlds most bad country consisting of people and president full of mentaly gone persons and the people there are causing the disturbance and very much problem in the whole of the world.France be aware that one day there will be no france but you will be highly abused of your bad acts.France go to hell.";
protest = protest.replace(/(.{100})/g, "$1<br>");
document.write(protest);