【发布时间】:2020-09-03 14:42:56
【问题描述】:
我想将一个字符串拆分为 10 个字符。但我不想拆分为一个单词。
因此字符串“还有九个字符 - 然后还有更多”将被拆分为 ["Nine", "characters", "to go -", "then some", "more"]。
超过 10 个字符的单词可以拆分。
我使用正则表达式最接近的是.{1,10}(?<=\s)。
这会将“九个字符-然后更多”拆分为["Nine ", "haracters ", "to go - ", "then some "]。
但行为很奇怪。在示例字符串中,它完全跳过了字符“c”。在其他测试字符串中,它只会在单独的数组项中添加“-”,而只有破折号适合它之前的数组项。所以它在空格之后分裂。
我还尝试在空格 (.split(' ')) 上使用 .split(),并使用 .reduce() 或 for 循环将数组项连接到其他最多 10 个字符的数组项中。
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] );
}
}
}
结果:["Nine chara", "cters to g", "o - then s", "ome more"].
没有else if:["Nine", "characters", "to go -", "then some", "more"]
没有else if 其他字符串:["Paul van", "den Dool", "-", "Alphabet", "- word"]
这很接近,但“字母”不会与连字符连接,因为它们不适合。我尝试用else if 声明来捕捉它,但这又破坏了我不想破坏的单词,并且与上面的正则表达式的结果相同。
我在这个问题上已经筋疲力尽了,我需要蜂巢思维来解决这个问题。因此,非常感谢您对此提供任何帮助。
上下文
我正在尝试在具有最小字体大小的有限大小框中显示画布上的文本。我的解决方案是在必要时将用户可以输入的字符串分成多行。为此,我需要将字符串拆分为一个数组,对其进行循环并相应地定位文本。
【问题讨论】:
-
你得到了很多关于算法的答案来进行分割......但请记住,并非所有字母在画布中都有相同的大小,也许你应该测量文本查看
measureText@987654321 @你可能会在你真的不需要分裂的地方分裂 -
确实如此。老实说,还没有想到这一点。但在完整的上下文中,文本将显示在一个正方形中,该正方形将显示在网络摄像头流顶部的画布上。方块会贴在你的额头上。当您移动头部时,正方形的大小会发生变化,尤其是当您前后移动头部时。所以我想我必须先在画布中添加文本来测量它,然后进行所有计算才能正确显示它。这需要用实际上每 50 毫秒发生一次的正方形进行更新。这可能会使这种方法比我想象的要重。
-
可能会帮助您完成最初的任务:stackoverflow.com/a/54472418/3702797
标签: javascript arrays regex canvas text