Javascript函数将文本拆分为两个相同长度的字符串

Javascript function to split the text into two strings of the same length

本文关键字:两个 字符串 文本 函数 拆分 Javascript      更新时间:2023-09-26

是否有标准的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来查找"middle",尽管它与您的例子不同。如果你想让第一行通常更短,你可以用(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."  */

edit:记住"hello".slice(2.5)在JS中工作。