【问题标题】:How to format text into multiple lines in JavaScript如何在 JavaScript 中将文本格式化为多行
【发布时间】:2018-12-07 03:58:31
【问题描述】:

我想要做的是有一个文本“框”,它的宽度有一定的行长,而不会将任何单词切成两半。 我目前要做的是将文本切成n长的行,然后我试图通过知道下一个空格的时间来修复单词。 这是我目前拥有的,但它并不能完全起作用,只能修复一些单词

function TextBox(length,text){
  array = [];
  test = /[A-Za-z]+/g;
  //cutting the text up
  for (i= 0;i < Math.ceil(text.length / length); i ++){
    array.push(text.slice(i * length,Math.min((i + 1) * length,text.length)));
  }
  //in case it ruins the lines the first time round
  for (z = 0; z < 3; z++){
    //reformatting the code
    for (i = 0; i < array.length - 1; i ++){
      if (test.test(array[i][array[i].length - 1])){
        array[i] += array[i+1].substr(0,array[i+1].indexOf(' ') + 1);
        array[i + 1] = array[i + 1].substr(array[i + 1].indexOf(' ') + 1);
      }
    }
  }
  //for debugging
  console.log(array);
}
TextBox(5,"i like to eat cheese when I am hungry");

编辑 输入的一个例子是: “我饿的时候喜欢吃奶酪” 我想要类似的东西: [ “我喜欢”, “去吃”, “起司”, “当我”, “饿了” ] 我现在要出来的是: [ '我喜欢 ', '到 ', 'eat c',注意奶酪中的“c” “嘿嘿”, ' 什么时候 ', '我是 ', '挂', 'ry' ] 和饥饿的 "ry"

行长约为 n(本例中为 5)个字符。

我尝试添加和删除额外的 for 循环,但据我所知,它有助于格式化它。

如果你知道我做错了什么,或者更简单的方法,那就太好了。

【问题讨论】:

  • 你能发布几个输入和每个输入的预期输出吗?
  • 你的意思是换行吗?正如@CertainPerformance 所说,请添加输入和预期输出。

标签: javascript string formatting


【解决方案1】:

一种选择是构造一个在 5 个字符、4 个字符或 7 个字符等之间交替的正则表达式:

.....   // 5 characters
....    // 4 characters
......  // 6 characters
...     // 3 characters
....... // 7 characters

并在这些交替之前添加

(?! )

确保匹配的行不以空格开头,并以替换结束

(?= |$)

确保匹配在空格(或字符串结尾)之前结束。

然后,您所要做的就是在输入上执行模式.match

function TextBox(length,text){
   const alternations = Array.from(
     { length: length * 2 - 1 },
     (_, i) => {
       const charCount = i % 2 === 0
       ? length - i / 2
       : length + (i - 1) / 2 + 1;
       return '.'.repeat(charCount);
     }
   );
   // in case none of the above alternations matched, lazy-match characters
   // until coming to a character followed by a space or the end of the string:
   alternations.push('.+?');

   const pattern = new RegExp('(?! )(?:' + alternations.join('|') + ')(?= |$)', 'g');
   console.log(pattern);
   return text.match(pattern);
}
console.log(TextBox(5,"i like to eat cheese when I am hungry"));
console.log(TextBox(8,"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"));

【讨论】:

  • 这个方法好像跳过了字符串的最后一个单词/段,抱歉跳代码太快了,现在可以了
【解决方案2】:

这是另一个只使用数组split().reduce()

function TextBox(length,text){
  var array = [];  
  
  text.split(' ').reduce(function(prev, cur) {
    var next = [prev, cur].join(' ').trim();
    
    if (next.length <= length) {
    	return next;
    } else {
    	array.push(next);
    	return '';
    }
  });   
  
  console.log(array);
}

TextBox(5, 'i like to eat cheese when I am hungry');

TextBox(8, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 2022-11-29
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多