Reputation: 47
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:
Upvotes: 3
Views: 1619
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