如何使用Javascript或Ruby在大块文本中智能地添加换行符

How to Intelligently add line breaks to large blocks of text with Javascript or Ruby

本文关键字:文本 智能 换行符 添加 Javascript 何使用 Ruby      更新时间:2023-09-26

我正在寻找一个库或算法,它可以占用我的没有换行符的长文本块,并将其拆分为对人类可读性最有意义的段落。

Ex。

I am looking for a library or algorithm that can take my long block of text that has no line breaks and split it into paragraphs that mostly make sense to human readability. On a different note, there is something else.

对此:

I am looking for a library or algorithm that can take my long block of text that has no line breaks and split it into paragraphs that mostly make sense to human readability.
On a different note, there is something else.

如果你只想在点处换行,你可以使用(for js):

mybigline.split(". ").join("'n'n");

如果你还想将每一行格式化为maxlen图表,在单词处打断,你也可以在单词边界处打断每一段,比如:

var maxlen = 20;
var line = "vlaze lkdf lskdjf sldfsldfk sldkjf sldsd qsdkj qlskdj qlsdkj qlsdkj qlsdkj qlsdkj sldkfjsldfj fkj sldkfj s. qsldkjqsdlj. skdjhqksdjhqskjdq sd.";
// split into lines at dots
var par = line.split(". ");
var out = []
for (i in par) {
  // each line into words
  var pline = par[i].split(" ");
  var curline = "";
  for (j in pline) {
    // add words to output up to maxlength
    var curch = pline[j];
    if(curline.length + curch.length < maclent) {
      curline += curch + (pline.length==1?"":" ");
    } else {
      out.push(curline);
      curline = curch + (pline.length==1?"":" ");    
    }
  }
  out.push(curline);
  out.push("'n");
}
res = out.join("'n");
alert(res);

https://jsfiddle.net/37Lbj701/