Skip to content
Advertisement

Adding new line after every 15 characters in JavaScript

I have used following method to do the changes, but I’m getting additional spaces after adding the new line. I used trim(), but it makes the value meaningless.

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());

Advertisement

Answer

Are you talking about the space on the last line of the output Throt ? There’s actually no more data there, but if you want your input string to repeat so that it fills in the rest of that space, you’ll need to repeat it so that it fills it as much as possible.

The base string of ER Throttle Position (with ending space) is 21 characters long. For a line length of 15, repeating the base string 5 times would result in 7 lines of repeated text that fills in the full width (unless you’re counting the final space):

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;
}
<output></output>

Changes made in my code:

  • Added two parameters to generalize the function to add new lines every position characters
  • Added a line to display spaces using underscores _ (optional)
  • Commented the assignment of result to columnValue before returning columnValue
  • Returned result instead
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement