每行放100个单词

时间:2017-10-12 21:09:09

标签: javascript arrays for-loop

我有一个问题,我通过一段大约1000字等的单词,并假设将单词划分为空格,最多100个字符的行长度。行长度应尽可能接近但不超过每行100个字符的限制。

问题是我只是每100个字符拆分字符串(忽略单词)。由于我正在舍入,这意味着在最后一次迭代时可能会遗留一些字符。

我想知道是否有人可以帮助我解决这个问题,并创建一个更好的功能来做到这一点

我的JS:

const paragraph = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam nibh. Nunc varius facilisis eros. Sed erat. In in velit quis arcu ornare laoreet. Curabitur adipiscing luctus massa. Integer ut purus ac augue commodo commodo. Nunc nec mi eu justo tempor consectetuer. Etiam vitae nisl. In dignissim lacus ut ante. Cras elit lectus, bibendum a, adipiscing vitae, commodo et, dui. Ut tincidunt tortor. Donec nonummy, enim in lacinia pulvinar, velit tellus scelerisque augue, ac posuere libero urna eget neque. Cras ipsum. Vestibulum pretium, lectus nec venenatis volutpat, purus lectus ultrices risus, a condimentum risus mi et quam. Pellentesque auctor fringilla neque. Duis eu massa ut lorem iaculis vestibulum. Maecenas facilisis elit sed justo. Quisque volutpat malesuada velit.",

  lines = Math.round(paragraph.length / 100);

let line = 0;

for (let i = 0; lines > i; i++) {
    document.body.innerHTML += paragraph.slice(line, line + 100) + '<br>';

小提琴链接:Here

我认为它的方式是,我们有N是&gt; = 1000我需要能够创建由行长度> = 100

的空格分隔的单词行

javascript不是我最强的观点,但我给了它一个去,所以任何帮助解决这个问题都会很棒。

3 个答案:

答案 0 :(得分:2)

你的段落是aprox 1000个单词,你不能保证有100个字符的倍数,因此最后一行可能会稍微减少。

你可能想先用每个单词拆分段落,我们假设没有花哨的格式,在这种情况下只是按每个空格分开。

var listWords = paragraph.split(" ");

现在你希望每一行最多100个字符,只需迭代单词并将它们添加到一行直到单词的长度太长

var line = "";
var lineLength = 0;
var fullBody = "";
for (var i = 0; i < listWords.length; i++){
   if (lineLength + listWords[i].length > 100){
     fullBody += line + "<br>";
     line = "";
     lineLength = 0;
   }
   line += listWords[i] + " ";
   lineLength += listWords[i].length + 1;
}
document.body.innerHTML += fullBody;

这是一个快速的解决方案,我确信它可以做得更好(不留下尾随空格),但它应该说明解决问题的方法。

根据Jonas的建议,让我们将innerHTML移到底部以加快速度。

答案 1 :(得分:2)

只要行不超过100个字符,就应该在空格上分割。 JSFiddle

var paragraph = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam nibh. Nunc varius facilisis eros. Sed erat. In in velit quis arcu ornare laoreet. Curabitur adipiscing luctus massa. Integer ut purus ac augue commodo commodo. Nunc nec mi eu justo tempor consectetuer. Etiam vitae nisl. In dignissim lacus ut ante. Cras elit lectus, bibendum a, adipiscing vitae, commodo et, dui. Ut tincidunt tortor. Donec nonummy, enim in lacinia pulvinar, velit tellus scelerisque augue, ac posuere libero urna eget neque. Cras ipsum. Vestibulum pretium, lectus nec venenatis volutpat, purus lectus ultrices risus, a condimentum risus mi et quam. Pellentesque auctor fringilla neque. Duis eu massa ut lorem iaculis vestibulum. Maecenas facilisis elit sed justo. Quisque volutpat malesuada velit.';

var result = '';
// While there's text left to parse
while(paragraph.length > 100){
    // Find the last space character in the first 100 characters
  var lastSpace = paragraph.substring(0,100).lastIndexOf(' ');

  // Add the chunk to the results
  result += paragraph.substring(0,lastSpace) + '<br/><br/>';

  // Remove the used chunk from the original body
  paragraph = paragraph.substring(lastSpace + 1);
}

// Add on the last trailing bit
result += paragraph;

document.body.innerHTML = result;

答案 2 :(得分:0)

您可以使用.slice()并通过100

增加传递给方法的参数
let chunks = paragraph.split(/\s/);

for (let i = 0, n = 100; i < chunks.length; i += 100, n += 100) {
  document.body.innerHTML += chunks.slice(i, n).join(" ") + '<br>';
}

jsfiddle https://jsfiddle.net/8gs78vra/18/

要获得每行100个字符,您可以使用.match().lastIndexOf().slice()

&#13;
&#13;
const paragraph = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam nibh. Nunc varius facilisis eros. Sed erat. In in velit quis arcu ornare laoreet. Curabitur adipiscing luctus massa. Integer ut purus ac augue commodo commodo. Nunc nec mi eu justo tempor consectetuer. Etiam vitae nisl. In dignissim lacus ut ante. Cras elit lectus, bibendum a, adipiscing vitae, commodo et, dui. Ut tincidunt tortor. Donec nonummy, enim in lacinia pulvinar, velit tellus scelerisque augue, ac posuere libero urna eget neque. Cras ipsum. Vestibulum pretium, lectus nec venenatis volutpat, purus lectus ultrices risus, a condimentum risus mi et quam. Pellentesque auctor fringilla neque. Duis eu massa ut lorem iaculis vestibulum. Maecenas facilisis elit sed justo. Quisque volutpat malesuada velit.";

let matches = paragraph.match(/.{100}|.+$/g);

let len = [];
      
for (let i = 0; i < matches.length; i++) {
  let str;
  if (matches[i][matches[i].length - 1] === " ") {
    str = matches[i].trim();
  } else {
    let index = matches[i].lastIndexOf(" ");
    str = matches[i].slice(0, index).trim();
    if (matches[i + 1]) {
      matches[i + 1] = matches[i].slice(index) + matches[i + 1];
    }  else {
      str = matches[i].slice(index + 1).trim();
    }
  }
  len.push(str.length);
  document.body.innerHTML += str + "<br>"
}

document.body.innerHTML += "<br>string .length of each line " + len;
&#13;
body {
  white-space:pre;
}
&#13;
&#13;
&#13;