在第10个字符之前的空白处在数组中拆分字符串

我想将一个字符串分割成10个字符,但是我不想在一个单词内分割。

So the string "Nine characters to go - then some more" would be split in ["Nine", "characters", "to go -", "then some", "more"].
The word can split if it's more than 10 characters.

The closest I got using regex was .{1,10}(?<=\s).
That would split "Nine characters to go - then some more" into ["Nine ", "haracters ", "to go - ", "then some "].
But the behaviour is weird. In the example string it completely skips the character "c". In other test strings it would only add "- " in a separate array item when just the dash would fit in with the array item before it. So it splits after the whitespace.

I also attempted to .split() on white spaces (.split(' ')) and using .reduce() or a for loop to join array items into other array items of max 10 characters.

for ( i = 0; i < splitArray.length; i++ ) {
  if ( i === 0 ) {
    // add first word in new array. Doesn't take into account yet that word can be longer than 10 characters
    newArray.push( splitArray[i] );
  } else {
    if ( newArray[ newArray.length - 1 ].length + splitArray[i].length + 1 < 10 ) {
      // if next word fits with the word in the new array (taking space into account), add it to 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 only part to it and add the rest in separate item in newArray
      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 {
      // push new item in 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"]
Without the else if other string: ["Paul van", "den Dool", "-", "Alphabet", "- word"]
This is close, but "Alphabet" won't join with the hyphen, because together they don't fit. I tried catching that with an else if statement but that is breaking words again that I don't want to break and is the same result as the regex above.

在这个问题上我的头脑已经枯竭了,为此我需要蜂巢的头脑。因此,对此非常有帮助。

语境 我正在尝试以最小字体在有限尺寸的框中在画布上显示文本。我的解决方案是在必要时将用户可以输入的字符串分成多行。为此,我需要将字符串拆分为数组,在其上循环并相应地放置文本。

评论