Flipwon
Flipwon

Reputation: 47

Cut string into chunks without breaking words based on max length

I have a string that I would like to break down into an array.

Each index needs to have a max letter, say 15 characters. Each point needs to be at a words end, with no overlap of the maximum characters (IE would stop at 28 chars before heading into next word).

I've been able to do similar things using regex in the past, but I'm trying to make this work with an online platform that does not like regex.

Example string: Hi this is a sample string that I would like to break down into an array!

Desired result @ 15 char max:

  1. Hi this is a
  2. sample string
  3. that I would
  4. like to break
  5. down into an
  6. array!

Upvotes: 3

Views: 1619

Answers (1)

SJxD
SJxD

Reputation: 269

Considering there's no word bigger then max limit

function splitString (n,str){
    let arr = str?.split(' ');
    let result=[]
    let subStr=arr[0]
    for(let i = 1; i < arr.length; i++){
        let word = arr[i]
        if(subStr.length + word.length + 1 <= n){
            subStr = subStr + ' ' + word
        }
        else{
            result.push(subStr);
            subStr = word
        }
    }
    if(subStr.length){result.push(subStr)}
    return result
}
console.log(splitString(15,'Hi this is a sample string that I would like to break down into an array!'))

Upvotes: 7

Related Questions