【问题标题】:Adding new line after every 15 characters in JavaScript在 JavaScript 中每 15 个字符后添加新行
【发布时间】:2021-11-05 10:15:14
【问题描述】:

我已使用以下方法进行更改,但在添加新行后我得到了额外的空格。 我使用了 trim(),但它使值毫无意义。

function addSpace() {
  var columnValue = "ER Throttle Position ER Throttle Position ER Throt";
  var result = "";
  while (columnValue.length > 0) {
    result += columnValue.substring(0, 15) + "\n";
    columnValue = columnValue.substring(15);
  }
  columnValue = result;

  return columnValue;
}

console.log(addSpace());

【问题讨论】:

  • 我在 chrome 控制台中运行了你的代码,它似乎工作正常
  • 我已将您的代码封装在一个函数 addSpace 中,它按预期工作。你还想要什么?
  • @decpk 感谢您的说明,终于对我有用。

标签: javascript newline


【解决方案1】:

你说的是输出 Throt 最后一行的空格吗?那里实际上没有更多数据,但是如果您希望输入字符串重复以填充该空间的其余部分,则需要重复它以尽可能多地填充它。

ER Throttle Position 的基本字符串(以空格结尾)长度为 21 个字符。对于 15 行长度,重复基本字符串 5 次将导致 7 行重复文本填满整个宽度(除非您计算最后的空格):

const output = document.getElementsByTagName("output")[0];

function addNewLine(columnValue = "", position = 0) {
  if (columnValue === "" || position === 0) {
    return "";
  }
  // Replacing spaces with underscore for visual representation
  columnValue = columnValue.replaceAll(" ", "_");
  let result = "";
  while (columnValue.length > 0) {
    result += columnValue.substring(0, position) + "\n";
    columnValue = columnValue.substring(position);
  }
  //columnValue = result;

  return result;
}

function print(message = "") {
  output.innerHTML += `<pre>${message}</pre>`;
}

print(addNewLine("ER Throttle Position ER Throttle Position ER Throt", 15));
print(addNewLine("ER Throttle Position ER Throttle Position ER Throttle Position ER Throttle Position ER Throttle Position ", 15));
pre {
  border: 1px solid black;
  max-width: 7.5rem;
  padding: 0.5rem;
}

pre::before {
  border-bottom: 2px solid green;
  content: "0123456789abcde";
  display: block;
  margin-bottom: 0.5rem;
}
&lt;output&gt;&lt;/output&gt;

对我的代码所做的更改:

  • 添加了两个参数来概括功能,以每position 个字符添加新行
  • 添加了一行以使用下划线 _ 显示空格(可选)
  • 在返回 columnValue 之前将 result 分配给 columnValue 进行了注释
  • 改为返回result

【讨论】:

  • 太好了,对我帮助很大。谢谢
猜你喜欢
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-17
  • 2022-09-22
  • 1970-01-01
  • 2022-11-22
相关资源
最近更新 更多