How to split a string into x characters or less, and only in space ("")?

I am creating a program that breaks a string into x characters and only in space ("").

Input paragraph:

There was no way to take a walk that day. In fact, we wandered around a leafless bush at one in the morning; but after lunch (Mrs. Reed, when there was no company, dined early), the cold winter wind brought with it clouds that were so gloomy, and rain that way

Input delimiter characters: 30

Now I get the output as follows:

var textArray = ["There was no possibility of ta","king a walk that day. We had b","een wandering, indeed, in the ","leafless shrubbery an hour in ","the morning; but since dinner ","(Mrs. Reed, when there was no ","company, dined early) the cold"," winter wind had brought with ","it clouds so sombre, and a rai","n so "]`

But I only want splits in space (). It is broken in the last space before the specified number of characters.

I need the output as follows:

var textArray = ["There was no possibility of", "taking a walk that day. We", "had been wandering, indeed, in", "the leafless shrubbery an hour", "in the morning; but since", "dinner (Mrs. Reed, when there", "was no company, dined early)", "the cold winter wind had", "brought with it clouds so", "sombre, and a rain so", "penetrating, that further", "out-door exercise was now out", "of the question."]`

I tried this code:

function textToArray() {
       var str = document.getElementById('stringg').value;
       var strArr = [];
       var count = parseInt(document.getElementById('numberOfWords').value, 10) || 1;

       for (var i = 0; i < str.length; i = i + count) {
            var j = i + count;
            strArr.push(str.substring(i,j));
       }
}
+4
source share
4 answers

array.reduce:

var str = "There was no possibility of taking a walk that day. We had been wandering, indeed, in the leafless shrubbery an hour in the morning; but since dinner (Mrs. Reed, when there was no company, dined early) the cold winter wind had brought with it clouds so sombre, and a rain so";
str = str.split(' ').reduce((m, o) => {
    var last = m[m.length - 1];
    if (last && last.length + o.length < 30) {
        m[m.length - 1] = `${last} ${o}`;
    } else {
        m.push(o);
    }
    return m;
}, []);
console.log(str);
Hide result
+4

( )

var input = "There was no possibility of taking a walk that day. We had been wandering, indeed, in the leafless shrubbery an hour in the morning; but since dinner (Mrs. Reed, when there was no company, dined early) the cold winter wind had brought with it clouds so sombre, and a rain so";

function splitter(input, maxChars) {
  var output = [];
  output.push( input.split(" ").reduce(function(a, b) {
    if (a.length + b.length < maxChars) {
      a += " " + b; //if comnined length is still not execeeding add it a
    } else {
      output.push(a); //if combined less is exceeding the maxchars then push the last sentence to output
      a = b;
    }
    return a;
  })); //push the residue to output
  return output;
}

console.log( splitter( input, 30 ) );
Hide result
+4

I would loop over the text, the definition of the current char is a valid delimiter, and if not, go looking for the closest space.

const
  input = 'There was no possibility of taking a walk that day. We had been wandering, indeed, in the leafless shrubbery an hour in the morning; but since dinner (Mrs. Reed, when there was no company, dined early) the cold winter wind had brought with it clouds so sombre, and a rain so';
  
function splitText(text, maxLength = 30) {
  const 
    result = [];

  // Keep looping till the input string is empty.
  while (text !== '') {
    // Initialize endIndex to the specified max length for the substring.
    let 
      endIndex;
      
    // A: If the max length is more than the remaining text length, adjust the 
    //    end index so it coincides with the remaining text length.
    // B: Else check if the character at the max length is NOT a space, in this 
    //    case go looking to a space as close to the max length as possible.
    if (maxLength > text.length) {  // [A]
      endIndex = text.length;
    } else if (text.substring(maxLength, 1) !== ' ') { // [B}
      endIndex = text.lastIndexOf(' ', maxLength);
    } else {
      endIndex = maxLength;
    }
    // Take the string with the determined length and place it in the result array.
    result.push(text.substring(0, endIndex));
    // Adjust the input string, remove the part that was just pushed into the result.
    text = text.substr(endIndex).trim();
  }

  return result;
}


console.log(splitText(input));
Run codeHide result
+1
source

You can take the last element of the array and check if the length of / equa is less than expacted, then concat the temporary line into the result set, otherwise the last line and the actual element will be concatenated into the result set.

var string = "There was no possibility of taking a walk that day. We had been wandering, indeed, in the leafless shrubbery an hour in the morning; but since dinner (Mrs. Reed, when there was no company, dined early) the cold winter wind had brought with it clouds so sombre, and a rain so";

string = string.split(' ').reduce(function (r, a) {
    var last = r.pop() || '',
        temp = last + (last && ' ') + a;
    return r.concat(temp.length <= 30 ? temp : [last, a]);
}, []);

console.log(string);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run codeHide result

With ES6, you can take a recursive approach with the rest operator and use the first parameter to add the string until it gets the desired length, and then return that part.

function join(a, b, ...rest) {
    if (!b) {
        return [a];
    }
    return a.length + b.length < 30
        ? join(a + ' ' + b, ...rest)
        : [a, ...join(b, ...rest)];
}

var string = "There was no possibility of taking a walk that day. We had been wandering, indeed, in the leafless shrubbery an hour in the morning; but since dinner (Mrs. Reed, when there was no company, dined early) the cold winter wind had brought with it clouds so sombre, and a rain so";

console.log(join(...string.split(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run codeHide result
0
source

Source: https://habr.com/ru/post/1688807/


All Articles