Skip to content

Instantly share code, notes, and snippets.

@billymoon
Created December 30, 2015 19:56
Show Gist options
  • Save billymoon/91db9ccada62028b50c7 to your computer and use it in GitHub Desktop.
Save billymoon/91db9ccada62028b50c7 to your computer and use it in GitHub Desktop.
near identical implementation of wordwrap from php.js
// slight discrepency with...
// var str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias veritatis, quis sunt cumque quod, dolorum! Itaque, inventore, sed. Nisi natus illum minima architecto, reprehenderit fugiat repellendus doloremque dolore adipisci aspernatur? suscipit, esse delectus tempora dolor aliquam excepturi, tempore non mollitia eum dolorem quidem eius quasi est, explicabo eos doloremque. Impedit! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, dolores, perferendis. At perferendis porro quidem in praesentium quia fuga nihil fugiat ratione. Provident, minima labore blanditiis mollitia sit voluptatibus quod.";
// wordwrap(str, 60, '\n', 2);
// but pretty close to functionally equavalent.
function wordwrap(str, intWidth, strBreak, cut) {
intWidth = typeof intWidth !== 'undefined' ? intWidth : 75;
strBreak = typeof strBreak !== 'undefined' ? strBreak : '\n';
cut = typeof cut !== 'undefined' ? cut : 0;
str += '';
if (intWidth <= 0) {
return str;
}
var result = [];
var lines = str.split(/\r\n|\n|\r/);
for(var i = 0; i < lines.length; i++){
var endPosition, segment, nextSegment,
out = '',
line = lines[i];
while (line.length > intWidth) {
line = line.replace(/^\s\b/, '') || true;
segment = line.slice(0, intWidth + 1).match(/\S*(\s)?$/);
if (cut === 2 || !!segment[1]) {
endPosition = intWidth;
} else if (segment.input.length - segment[0].length) {
endPosition = segment.input.length - segment[0].length;
} else if (cut === 1) {
endPosition = intWidth;
} else {
nextSegment = line.slice(intWidth).match(/^\S*/);
endPosition = segment.input.length + nextSegment[0].length;
}
out += line.slice(0, endPosition);
line = line.slice(endPosition);
if (!!line && line.length) {
out += strBreak;
}
}
result.push(out+line);
}
return result.join('\n');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment