JS: Splitting a long string into strings with char limit while avoiding splitting words

I am trying to take a large block of text and split it into multiple strings that are 148 characters each, while avoiding cutting off words.

I have this now, which is splitting words:

var length = shortData.new.length;

if (length < 160){

  outputString[0] = shortData.new;


if (length > 160 && length < 308){

  outputString[0] = shortData.new.substring(0,148);
  outputString[1] = shortData.new.substring(148,length);    



if (length > 308 && length < 468){

  outputString[0] = shortData.new.substring(0,148);
  outputString[1] = shortData.new.substring(148,308);   
  outputString[2] = shortData.new.substring(308,length);    



if (length > 468 && length < 641){

  outputString[0] = shortData.new.substring(0,148);
  outputString[1] = shortData.new.substring(148,308);   
  outputString[2] = shortData.new.substring(308,468);   
  outputString[3] = shortData.new.substring(468,length);    





You can use this function, just pass in your string and the length and it will return the array, like:

var outputString = splitter(shortData['new'], 148);

The function:

function splitter(str, l){
    var strs = [];
    while(str.length > l){
        var pos = str.substring(0, l).lastIndexOf(' ');
        pos = pos <= 0 ? l : pos;
        strs.push(str.substring(0, pos));
        var i = str.indexOf(' ', pos)+1;
        if(i < pos || i > pos+l)
            i = pos;
        str = str.substring(i);
    return strs;

Example usage:

splitter("This is a string with several characters.\
120 to be precise I want to split it into substrings of length twenty or less.", 20);


["This is a string","with several","characters. 120 to",
"be precise I want","to split it into","substrings of",
"length twenty or","less."]

You are going to have to pad some of your strings, to make them have the number of characters you require.

var lines= s.match(/(.{1,147}\s)\s*/g);

You could use lastIndexOf() on a substr() of length 148 to find where to break the original string, remove that and loop while the length is > 148, like this:

var myText = "ad aenean adipiscing elit eget eleifend phasellus aenean lobortis vero venenatis ultricies eget iaculis ac neque nibh dignissim eleifend erat et in in justo sollicitudin mattis maecenas purus quis mi sed molestie integer magna non hendrerit nulla id neque augue suspendisse in in eget consectetuer et cubilia eu ullamcorper morbi elementum sed sed pharetra quam velit ante pellentesque eros nullam lobortis lorem fringilla libero elit nonummy purus sodales mauris sagittis praesent aenean in ut nullam ultricies quam aliquam arcu quisque semper lacinia lacinia sodales imperdiet ante venenatis suspendisse amet ante tellus nec nibh lorem in viverra magna cursus elit erat lobortis mattis purus pellentesque velit pellentesque dolor quam id mauris nibh pellentesque augue vel posuere aptent varius vivamus parturient hac ligula libero a varius sollicitudin sed dictumst morbi eros vestibulum donec purus turpis urna vel nisl quisque vulputate tristique non sed risus viverra varius tincidunt hendrerit ac dui mollis quam nunc suspendisse mattis volutpat vulputate integer ipsum cursus erat justo eu vestibulum sed blandit ac mi ligula montes sollicitudin vitae vel lacus imperdiet orci tincidunt sed imperdiet nunc vehicula pellentesque orci gravida diam non ut wisi sit et massa congue id scelerisque et mauris arcu nunc litora dignissim urna ea nullam magna felis duis pellentesque ultricies tincidunt vel pede fusce nunc sed interdum cursus wisi qui pulvinar wisi consectetuer fames sed hendrerit vitae velit viverra malesuada eu magna vehicula vivamus augue sagittis curabitur rutrum fringilla vivamus nisl enim eros elit vestibulum duis et duis erat sit auctor ac ipsum in et lacinia eu magna accumsan in nulla a sed massa maecenas ultricies duis dignissim sem augue id posuere lacus felis nisl quam ultricies urna dui curabitur morbi ante ut est eget tellus pulvinar mollis elementum tellus malesuada sollicitudin ligula fusce eget libero metus cras ligula felis nunc porttitor sit at";
var MAX_LENGTH = 148;

while (myText.length > MAX_LENGTH) {
    var s = myText.substr(0, MAX_LENGTH);
    var i = s.lastIndexOf(" ");
    alert(myText.substr(0, i));
    myText = myText.substr(i + 1, myText.length);

Without thinking to much about it, I would do something like this, just not in pseudo code

if string length > 148
    for i=148;i<string length;i+148
        if character at i = space
            add substring(i-148 to i) to output[]
            add substring(i-148 to lastindoxof space) to output[]
            set i to lastindoxof space + 1)
    if i-148 != string length
        add substring (i-148 to string length -1) to output[]


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.