Question

Remove a Trailing Newline from a String in JavaScript

pythonnewlinetrailing

Question

How can I remove the last character of a string only if that character is a newline?

Example:

"abc\n" // becomes "abc"

If the string does not end with a newline, it should remain unchanged.

Short Answer

By the end of this page, you will understand how to remove a trailing newline from a string in JavaScript, when to use slice(), when a regular expression is more useful, and how to avoid accidentally removing characters you wanted to keep.

Concept

A trailing newline means a line break character at the end of a string.

In JavaScript, the most common newline characters are:

  • \n — line feed
  • \r\n — carriage return + line feed, commonly used in Windows-style text

Removing a trailing newline is a common string-cleaning task. You often need it when:

  • reading user input
  • processing text files
  • cleaning API responses
  • preparing log lines
  • normalizing pasted content

The important idea is: only remove the newline if it appears at the end. You usually do not want to remove newlines from the middle of the string.

There are two common approaches:

  1. Check the end of the string, then remove one character
  2. Use a regular expression to remove newline characters at the end

The first approach is simple and readable for basic cases. The second is more flexible, especially if you want to support both \n and \r\n.

Mental Model

Think of a string like a piece of paper with text on it.

  • The content is the writing.
  • A trailing newline is like an extra blank line added at the very bottom.

You are not rewriting the whole paper. You are just checking the very end to see whether there is one unnecessary line break and trimming it off.

So the task is not “remove newlines everywhere.” It is “inspect the last edge of the string and clean it only if needed.”

Take Quiz

Syntax and Examples

The simplest approach is to check whether the string ends with \n and then remove the last character.

const str = "abc\n";
const result = str.endsWith("\n") ? str.slice(0, -1) : str;

console.log(result); // "abc"

How it works

  • endsWith("\n") checks the last character
  • slice(0, -1) returns everything except the last character
  • If there is no trailing newline, the original string is returned

Example with no trailing newline

const str = "abc";
const result = str.endsWith("\n") ? str.slice(0, -1) : str;

console.log(result); // "abc"

Using a regular expression

If you want to remove a newline at the end in a more compact way:

const str = "abc\n";
const result = str.replace(/\n$/, "");

console.log(result); // "abc"
  • /\n$/ means:
    • \n = newline character
    • $ = end of the string

Supporting Windows-style line endings

Some strings may end with \r\n instead of just \n.

const str = "abc\r\n";
const result = str.replace(/\r?\n$/, "");

console.log(result); // "abc"
  • \r? means an optional carriage return
  • This matches both "abc\n" and "abc\r\n"

Removing multiple trailing newlines

If you want to remove all newline characters at the end:

const str = "abc\n\n\n";
const result = str.replace(/[\r\n]+$/, "");

console.log(result); // "abc"

This removes one or more trailing \r or \n characters.

Step by Step Execution

Consider this example:

const str = "hello\n";
const result = str.endsWith("\n") ? str.slice(0, -1) : str;
console.log(result);

Step by step

  1. str is assigned the value "hello\n"
  2. str.endsWith("\n") checks whether the final character is a newline
  3. The check returns true
  4. Because the condition is true, JavaScript runs str.slice(0, -1)
  5. slice(0, -1) starts at index 0 and stops before the last character
  6. The returned value is "hello"
  7. result now stores "hello"
  8. console.log(result) prints:
hello

Another trace

const str = "hello";
const result = str.endsWith("\n") ? str.slice(0, -1) : str;
console.log(result);
  1. str is "hello"
  2. endsWith("\n") returns false
  3. Because the condition is false, JavaScript keeps the original string
  4. result becomes "hello"
  5. Output stays unchanged

Real World Use Cases

Here are common situations where removing a trailing newline is useful:

Processing text files

When reading lines from files, the final line may include a newline character that you do not want in later processing.

const cleaned = line.replace(/\r?\n$/, "");

Cleaning user input

Users may paste text with an extra line break at the end.

const message = input.replace(/\r?\n$/, "");

Preparing API data

Some external systems return text with a final newline. Before storing or comparing the value, you may normalize it.

const token = responseText.replace(/\r?\n$/, "");

Log processing

Log lines often end with newlines. If you are combining or formatting them, you may remove the final newline first.

CLI tools and scripts

Command-line output frequently includes trailing line breaks. Scripts often trim only the final newline before further parsing.

Take Quiz

Real Codebase Usage

In real projects, developers usually wrap this logic in a small utility function so it is easy to reuse and test.

function removeTrailingNewline(str) {
  return str.replace(/\r?\n$/, "");
}

This pattern is useful because:

  • the intent is clear
  • the logic is reused consistently
  • Windows and Unix line endings can be handled in one place

Common patterns

Validation before processing

function normalizeUsername(raw) {
  if (typeof raw !== "string") {
    throw new TypeError("Expected a string");
  }

  return raw.replace(/\r?\n$/, "");
}

Early return

function removeTrailingNewline(str) {
  if (!str.endsWith("\n")) {
    return str;
  }

  return str.slice(0, -1);
}

Normalization utilities

In larger codebases, string cleanup is often part of a normalization step before storing, comparing, or displaying data.

function normalizeLine(str) {
  return str.replace(/\r?\n$/, "").trim();
}

Use this carefully: trim() removes more than just a trailing newline.

Common Mistakes

1. Removing the last character without checking

Broken example:

const str = "abc";
const result = str.slice(0, -1);

console.log(result); // "ab"

This always removes the last character, even when it is not a newline.

Fix: check first, or use a regex that only matches the end newline.

const result = str.endsWith("\n") ? str.slice(0, -1) : str;

2. Using trim() when you only want to remove one trailing newline

Broken example:

const str = "  abc\n";
const result = str.trim();

console.log(result); // "abc"

This removes:

  • leading spaces
  • trailing spaces
  • trailing newline

That may be too aggressive.

3. Forgetting about \r\n

Broken example:

const str = "abc\r\n";
const result = str.replace(/\n$/, "");

console.log(result); // "abc\r"

Only \n is removed, leaving \r behind.

Fix:

const result = str.replace(/\r?\n$/, "");

4. Removing all newlines instead of just the trailing one

Broken example:

const str = "a\nb\nc\n";
const result = str.replace(/\n/g, "");

console.log(result); // "abc"

This removes every newline in the string, including meaningful ones in the middle.

Fix: use $ to target only the end.

const result = str.replace(/\n$/, "");

5. Assuming strings are changed in place

Strings in JavaScript are immutable.

Broken example:

let str = "abc\n";
str.replace(/\n$/, "");
console.log(str); // still "abc\n"

Fix: assign the result.

str = str.replace(/\n$/, "");

Comparisons

ApproachExampleBest forNotes
endsWith() + slice()str.endsWith("\n") ? str.slice(0, -1) : strSimple casesVery readable
replace(/\n$/, "")str.replace(/\n$/, "")Remove one Unix newlineCompact, but does not handle \r\n alone
replace(/\r?\n$/, "")str.replace(/\r?\n$/, "")Cross-platform line endingsUsually the safest single-newline option
replace(/[\r\n]+$/, "")str.replace(/[\r\n]+$/, "")Remove multiple trailing newlinesGood for cleanup tasks
trimEnd()str.trimEnd()Remove all trailing whitespaceRemoves spaces and tabs too, not just newlines
trim()str.trim()Remove whitespace on both endsToo broad if you only want a newline

slice() vs replace()

  • Use slice() when you know you want to remove exactly one final character after checking it.
  • Use replace() when pattern matching makes the intent clearer, especially for \r\n.

trimEnd() vs removing a trailing newline

const str = "abc   \n";

console.log(str.trimEnd());           // "abc"
console.log(str.replace(/\r?\n$/, "")); // "abc   "

trimEnd() removes all trailing whitespace, while the regex removes only the newline.

Take Quiz

Cheat Sheet

Remove one trailing \n

str.endsWith("\n") ? str.slice(0, -1) : str

or

str.replace(/\n$/, "")

Remove one trailing \n or \r\n

str.replace(/\r?\n$/, "")

Remove multiple trailing line breaks

str.replace(/[\r\n]+$/, "")

Important rules

  • Strings are immutable in JavaScript
  • replace() returns a new string
  • $ means end of string in regex
  • trim() and trimEnd() remove whitespace, not just newlines

Safe default

function removeTrailingNewline(str) {
  return str.replace(/\r?\n$/, "");
}

Edge cases

"abc"        // unchanged
"abc\n"      // becomes "abc"
"abc\r\n"   // becomes "abc"
"abc\n\n"   // removes only one if using /\r?\n$/

FAQ

How do I remove a newline only at the end of a string in JavaScript?

Use either:

str.endsWith("\n") ? str.slice(0, -1) : str

or, more flexibly:

str.replace(/\r?\n$/, "")

What is the difference between trim() and removing a trailing newline?

trim() removes whitespace from both ends of the string, including spaces, tabs, and newlines. Removing a trailing newline targets only the line break at the end.

How do I handle Windows newlines in JavaScript?

Use:

str.replace(/\r?\n$/, "")

This supports both \n and \r\n.

Does replace() modify the original string?

No. JavaScript strings are immutable. replace() returns a new string, so you must store the result.

How can I remove multiple trailing newlines?

Use:

str.replace(/[\r\n]+$/, "")

Should I use slice() or regex for this?

Use slice() for simple, readable logic when checking one final \n. Use regex when you need to handle \r\n or multiple line endings more easily.

Take Quiz

Mini Project

Description

Build a small text-cleaning utility that normalizes lines before saving them. This demonstrates how to safely remove a trailing newline without changing the rest of the content.

Goal

Create a function that removes one trailing newline from a string and test it with several inputs.

Requirements

  1. Write a function that accepts a string.
  2. Remove one trailing newline if the string ends with \n or \r\n.
  3. Leave the string unchanged if it has no trailing newline.
  4. Test the function with at least three different inputs.
  5. Print the original and cleaned values.
Take Quiz

Keep learning

Related questions

View more