Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!
like image 604
Flipwon Avatar asked Mar 25 '26 04:03

Flipwon


1 Answers

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!'))
like image 176
SJxD Avatar answered Mar 27 '26 16:03

SJxD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!