是否有标准的javascript函数将字符串分成相同(或几乎相同)行的两行而不会破坏单词。
我真正想要的是:
-如果文本中的字符数少于50个(包括空格),则保留文本不变。
-否则,将其分成长度相同(几乎相同)的两行。
为了以一种良好的方式显示文本,使它看起来更好,这是必需的。
例子:
Today is Monday.
Today is Monday, tomorrow is Tuesday. //less than 50 symbols.
Today is Monday, tomorrow is
Tuesday, after tomorrow is Wednesday. //splitted into two lines, Tuesday is on the second line.
一个简单的示例使用split查找“中间”,尽管它与您的示例不同。如果您希望第一行通常更短,则可以使用(s.length / 2)-6向左移几个分割槽。您甚至可以考虑尝试(s.length * 0.45)向左移一点;玩转,找到最适合您的文字的内容。
以下是找到中间附近空间的位置的方法:
var s="Today is Monday, tomorrow is Tuesday, after tomorrow is Wednesday.";
var p=s.slice(s.length/2).split(" ").slice(1).join(" ").length;
s.slice(0, s.length-p) + "\n" + s.slice(s.length-p);
/* == "Today is Monday, tomorrow is Tuesday,
after tomorrow is Wednesday." */
编辑:请记住,“ hello” .slice(2.5)在JS中有效。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句