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:
- Check the end of the string, then remove one character
- 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.”
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 characterslice(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:
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
stris assigned the value"hello\n"str.endsWith("\n")checks whether the final character is a newline- The check returns
true - Because the condition is true, JavaScript runs
str.slice(0, -1) slice(0, -1)starts at index0and stops before the last character- The returned value is
"hello" resultnow stores"hello"console.log(result)prints:
hello
Another trace
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.
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()) {
str;
}
str.(, -);
}
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
Comparisons
| Approach | Example | Best for | Notes |
|---|---|---|---|
endsWith() + slice() | str.endsWith("\n") ? str.slice(0, -1) : str | Simple cases | Very readable |
replace(/\n$/, "") | str.replace(/\n$/, "") | Remove one Unix newline | Compact, but does not handle \r\n alone |
replace(/\r?\n$/, "") | str.replace(/\r?\n$/, "") | Cross-platform line endings | Usually the safest single-newline option |
replace(/[\r\n]+$/, "") |
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 regextrim()andtrimEnd()remove whitespace, not just newlines
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.
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
- Write a function that accepts a string.
- Remove one trailing newline if the string ends with
\nor\r\n. - Leave the string unchanged if it has no trailing newline.
- Test the function with at least three different inputs.
- Print the original and cleaned values.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.