What does the Trim Trailing Spaces Tool do?
The Trim Trailing Spaces Tool removes invisible trailing whitespace characters (spaces and tabs) from the ends of lines in source code, markdown documents, and raw text files. It also offers options to trim leading whitespace and remove lines that become empty after trimming.
Core Concepts
Understanding trailing whitespace removal:
- End-of-Line Trimming: Strips spaces and tabs immediately preceding newline breaks (
\nor\r\n). - Clean Version Control Diffing: Prevents Git diff pollution where lines appear changed solely due to unintentional space bars pressed at line ends.
- Optional Left Trimming: Removes leading whitespace and indents across the entire multiline payload when enabled.
How to use the tool?
- Enter Text or Code: Enter or paste your source code or multiline text payload into the editor or click Load Sample.
- Configure Options:
- Optionally toggle Also Trim Leading Spaces.
- Optionally toggle Remove Lines That Become Empty.
- Trim & Copy: Click Trim Trailing Whitespace, then click Copy or Download to save the sanitized output.
Related Developer Utilities
If you work with text cleaning, source code hygiene, and whitespace formatting, explore these complementary tools:
- Text Whitespace Cleaner: Normalize multiple consecutive spaces, tabs, and line breaks.
- Remove Empty Lines: Strip blank and whitespace-only lines from text.
- Tabs to Spaces Converter: Convert between tab stops and fixed space sequences.
- Text Diff Tool: Inspect line and character level differences between two documents.
REST API Integration
Blueutils provides a free REST API endpoint (POST https://blueutils.com/api/text/trim-trailing-spaces) to programmatically remove trailing spaces, tabs, and hidden whitespace characters from the end of every line in raw text or source code files.
API Request Parameters
| Name | Type | Description | Example |
|---|---|---|---|
rawText |
String | Input multiline raw text payload. | "const a = 1; \nconst b = 2;\t " |
trimLeadingToo |
Boolean | Optional. Also strip leading indentation spaces. Default: false. |
false |
removeEmptyLines |
Boolean | Optional. Remove lines that become empty. Default: false. |
false |
lineEndings |
String | Optional. Line ending normalization: "lf" or "crlf". Default: "lf". |
"lf" |
API Request Payload Examples
cURL
curl -X POST https://blueutils.com/api/text/trim-trailing-spaces \
-H "Content-Type: application/json" \
-d '{
"rawText": "const a = 1; \nconst b = 2;\t ",
"trimLeadingToo": false
}'Python
import requests
url = "https://blueutils.com/api/text/trim-trailing-spaces"
payload = {
"rawText": "const a = 1; \nconst b = 2;\t ",
"trimLeadingToo": False
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())Java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws Exception {
String jsonPayload = """
{
"rawText": "const a = 1; \\nconst b = 2;\\t ",
"trimLeadingToo": false
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://blueutils.com/api/text/trim-trailing-spaces"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}API Response Parameters
| Name | Type | Description | Example |
|---|---|---|---|
isValid |
Boolean | Indicates whether operation succeeded. | true |
result |
String | Cleaned multiline text payload with trailing spaces removed. | "const a = 1;\nconst b = 2;" |
API Response Payload Examples
Success Response (HTTP 200 OK)
{
"isValid": true,
"result": "const a = 1;\nconst b = 2;"
}Validation Failure Response (HTTP 400 Bad Request)
{
"isValid": false,
"error": "Input text payload cannot be empty."
}Rate Limit Exceeded Response (HTTP 429 Too Many Requests)
{
"error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}Why use an API to trim trailing spaces?
Integrating the Trim Trailing Spaces API into Git pre-commit hooks, CI/CD linting checks, or AI agent tool calling provides key benefits:
- Rapid Script Validation: Strips redundant trailing spaces before submitting pull requests or saving generated configuration files.
- Optimized Token Efficiency for AI Agents: LLMs frequently introduce invisible trailing whitespace in code blocks. Calling the API eliminates whitespace noise without consuming reasoning tokens.
- Deterministic Accuracy Without Hallucinations: Ensures 100% regex precision across CRLF and LF multiline files.
Native Usage
How to trim trailing whitespace locally in terminal environments or scripts:
Windows (CMD / PowerShell)
# Trim trailing spaces from lines in PowerShell
(Get-Content input.txt) | ForEach-Object { $_.TrimEnd() } | Set-Content cleaned.txtLinux / Unix (Bash)
# Strip trailing spaces using sed in Linux
sed -i 's/[ \t]*$//' input.txtPython
Using Python rstrip:
with open("input.txt", "r", encoding="utf-8") as f:
lines = [line.rstrip() for line in f]
with open("cleaned.txt", "w", encoding="utf-8") as f:
f.write("\n".join(lines))
print("Trailing spaces removed successfully.")Java
Using Java Streams:
import java.nio.file.*;
import java.util.*;
import java.util.stream.Collectors;
public class TrimTrailingExample {
public static void main(String[] args) throws Exception {
List<String> lines = Files.readAllLines(Paths.get("input.txt"));
List<String> cleaned = lines.stream()
.map(line -> line.replaceAll("[ \\t]+$", ""))
.collect(Collectors.toList());
Files.write(Paths.get("cleaned.txt"), cleaned);
System.out.println("Cleaned trailing spaces successfully.");
}
}