Skip to content

Instantly share code, notes, and snippets.

@abezhinaru
Last active July 24, 2017 11:44
Show Gist options
  • Save abezhinaru/d8c62d155659bb27a0934ee81fbf2622 to your computer and use it in GitHub Desktop.
Save abezhinaru/d8c62d155659bb27a0934ee81fbf2622 to your computer and use it in GitHub Desktop.
/**
* Function that separates a string value to line by symbols length;
*
* @param {String} string - input string
* @param {Number} lineLength - symbols length per line
* @param {Boolean} useSpaces - Take into account the gaps or not
* @returns {Array.<String>}
*/
const lineSplitter = (string, lineLength, useSpaces = true) => {
let result = [];
let frmString = string;
let lastSpaceRgx = /\s(?!.*\s)/;
while(frmString.length > 0) {
let line = frmString.substring(0, lineLength);
let nextIdx = lineLength;
if (useSpaces) {
// if space mod on, find the last space index and set as end index of substring
let idx = line.search(lastSpaceRgx);
if (idx > 0) {
line = line.substring(0, idx);
nextIdx = idx;
}
}
frmString = frmString.substring(nextIdx);
result.push(line);
}
return result;
};
// Example
const loremTest = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy";
const result = lineSplitter(loremTest, 20);
console.log(result); // result ["Lorem Ipsum is", " simply dummy text", " of the printing", " and typesetting", " industry. Lorem", " Ipsum has been the", " industry's", " standard", " dummy"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment