Skip to content Skip to sidebar Skip to footer

Break Long String At Specif Char And Max Length (js)

Probably there is an answser much cleaner and more working than mine, but i cannot find. So i did try for myself with not much result so far. This way i get things like the first

Solution 1:

So I took the time to actually make it work according to your criteria. All the steps are explained in the comments.

var str = "Persons: Amy, bertha, Charlie, Donkey, Evy, Felicia, Ghunter, Hercules, Indica, Jody, Katy, Linsay, Moony, Nigel, Opethry, Phil, Quinton, Ricial, Stefany, Trudy, Ursla, Vlinder, Wendy, Xion, Yvy, Zulu";
var maxCount = 100;
var splitNames = function(str, max){
    // ["person:","Amy,","bertha,",...]var names = str.split(' '),
        lines = [],
        line = 0,
        lineLength = 0;

    // loop through our array of names
    names.forEach(function(name){
        // if length is more than our maxif(lineLength + name.length + 1 > max){
            line += 1; // move to next line
            lineLength = 0; // reset length counter
        } else {
            lineLength += 1; // add 1 for the space we'll add later
        }
        // make sure we add an empty array if there isn't one
        lines[line] = lines[line] || [];
        
        // add the current name
        lines[line].push(name);
        
        // add name length to the line length
        lineLength += name.length;
    });
    
    return lines.map(function(line){
        // join our names with a space (which we counted toward the length)return line.join(' ');
    });
}
console.log(splitNames(str, maxCount));

Solution 2:

There are few things you miss. Most important one is that you should start next slice from startPoint, not from (i * maxCount) - maxCount. Another biggie is that lastIndexOf will count from start of the slice, not from start of the original string (which will be less then maxCount and then less then startPoint for all slices except first one). This is why second chunk is empty. Combined with the first biggie, it makes last chunk to start from "say", as it starts from position of last space in previous chunk.

You should also take care about last chunk to not cut off by last space as there might be no spaces at the end. And also take care of slices that might have no spaces in them. Finally, number of chunks might not be Math.floor(str.length / maxCount) even if str.length / maxCount is exact integer.

To illustrate the point, I took freedom to fix it the way I see what you are trying to do.

var str = "Persons: Amy, bertha, Charlie, Donkey, Evy, Felicia, Ghunter, Hercules, Indica, Jody, Katy, Linsay, Moony, Nigel, Opethry, Phil, Quinton, Ricial, Stefany, Trudy, Ursla, Vlinder, Wendy, Xion, Yvy, Zulu";
var maxCount = 100;
var jki = Math.floor(str.length / maxCount);
var arr = [];
var startPoint = 0;
while (startPoint < str.length) {
    while (startPoint < str.length && str[startPoint] == ',' ||  str[startPoint] == ' ') // chop leading commas and spaces off
    startPoint++;
    var nextSlice;
    var nextStart;
    if (startPoint + maxCount >= str.length) {
        // last chunk goes in completely
        nextSlice = str.slice(startPoint);
        nextStart = str.length;
    }
    else {
        // not last, chop of by last space if any
        nextSlice = str.slice(startPoint, startPoint + maxCount);
        nextStart = nextSlice.lastIndexOf(" ");
        if (nextStart <= 0) {
            nextStart = nextSlice.length;
        }
        else {
            nextStart -= 1;
        }
        nextStart += startPoint; // adjust for slice starting not at the beginning of str
     }
     arr.push(str.slice(startPoint, nextStart));
     startPoint = nextStart + 1;
}
console.log(arr);

Solution 3:

var str = "Persons: Amy, bertha, Charlie, Donkey, Evy, Felicia, Ghunter, Hercules, Indica, Jody, Katy, Linsay, Moony, Nigel, Opethry, Phil, Quinton, Ricial, Stefany, Trudy, Ursla, Vlinder, Wendy, Xion, Yvy, Zulu";

var arr = str.split(' ').map(word => word.substr(0, 100)).reduce((acc, word) => {
  acc.length += word.length + 1;
  if (acc.length > 100) {
    acc.length = word.length - 1;
    acc.lines.push([word]);
  } else {
    acc.lines[acc.lines.length - 1].push(word);
  }
  return acc;
},{lines: [[]], length: -1}).lines.map(line => line.join(' '));

console.log(arr);

Post a Comment for "Break Long String At Specif Char And Max Length (js)"