How can I split a string into segments of n characters? is similar but not exactly what we are trying to achieve:
// let splitSentence = (sentence, nChar) => {} // creating this function
let sentence = 'the quick cucumber fox jumps over the lazy dog.'
splitSentence(sentence, 15)
// output we are trying to get
// ['the quick cucumber', 'fox jumps over', 'the lazy dog.']
We cannot string split only on spaces, since multiple words are needed in each array element, not just a single word. The process, for nChar == 15
, 15 letters are counted into the string, which gets to the quick cucum
. The function should finish the word and add the quick cucumber
into the output array as first element, then continue counting from the remainder of the sentence, starting at the next word fox
, and repeat this process. Not sure if .match()
with start and end indexes works for our problem like it does for the SO post linked above.
Putting this logic into splitSentence(). So far we have:
let splitSentence = (sentence, nChar) => {
let output = [];
let i = 0;
while (i < sentence.length) {
let partOfSentence = sentence.slice(i, i + 15);
output.push(partOfSentence)
i = i + 15
}
return output;
}
However, getting ['the quick cucum', 'ber fox jumps o', 'ver the lazy do', 'g.']
, which is not what is needed. Not sure how to keep the entire word together in the slice when we loop over the string.