I am looking for a way to break a string into chunks of 10 characters without splitting words.
For example, the string "Nine characters to go - then some more" should be split into
["Nine", "characters", "to go -", "then some", "more"]
.Words longer than 10 characters can be split.
I tried using regex with .{1,10}(?<=\s)
.
However, the results were not as expected. It would sometimes skip characters or split at weird places like after a whitespace.
Another attempt involved using .split(' ')
and then using various techniques like .reduce()
or loops to achieve the desired result.
for ( i = 0; i < splitArray.length; i++ ) {
if ( i === 0 ) {
// first word in new array (no consideration for word length)
newArray.push( splitArray[i] );
} else {
if ( newArray[ newArray.length - 1 ].length + splitArray[i].length + 1 < 10 ) {
// if next word fits in current array item (considering space), add it
newArray[ newArray.length - 1 ] = newArray[ newArray.length - 1 ] + " " + splitArray[i];
} else if ( newArray[ newArray.length - 1 ].length + splitArray[i].length + 1 >= 10 ) {
// next word doesn't fit
// split word and add it to new array
const index = 9 - newArray[ newArray.length - 1 ].length
const prev = splitArray[i].slice( 0, index );
const next = splitArray[i].slice( index, splitArray[i].length );
newArray[ newArray.length - 1 ] = newArray[ newArray.length - 1 ] + " " + prev;
newArray.push( next );
} else {
// add new item to newArray
newArray.push( splitArray[i] );
}
}
}
Results in:
["Nine chara", "cters to g", "o - then s", "ome more"]
.Without the
else if
: ["Nine", "characters", "to go -", "then some", "more"]
Another example without the
else if
: ["Paul van", "den Dool", "-", "Alphabet", "- word"]
However, the word "Alphabet" does not join with the hyphen, which is a limitation.
I am stuck and seeking assistance from the community to solve this issue.
Context
I need to break a user-entered string into multiple lines for display on a canvas within a limited space and with a minimum font size. This involves splitting the string into an array, iterating over it, and positioning the text accordingly.