How to Remove Extra Spaces, Trim & Clean String Formatting Issues Online
String formatting bugs waste enormous amounts of developer time. Extra whitespace breaks JSON parsing. Wrong case causes API key mismatches. Special characters corrupt SQL queries. Trailing newlines break hash comparisons. These bugs are invisible until runtime and hard to spot in code reviews. Here is how to find and fix all of them fast — with real code examples and a free online tool.
Common string formatting bug
"Bearer mytoken \n" was sent instead of "Bearer mytoken"How to Remove Extra Spaces from a String
Extra spaces in strings come from user input fields, copy-pasted data, CSV exports, and log parsing. They are invisible in most text editors but cause real failures — a JSON key with a trailing space is a different key, an API token with a leading space returns 401, and a SQL value with extra spaces breaks exact-match queries.
String with extra spaces vs cleaned output
Raw input with spaces
" hello world "
// Leading space + collapsed spaces + trailing space
// JSON.parse will succeed but the key/value will have the spaces
// indexOf("hello world") returns -1Trimmed and collapsed
"hello world"
// No leading/trailing spaces
// Internal spaces collapsed to single spaces
// Exact matches work correctly// Remove leading and trailing whitespace only
const cleaned = str.trim();
// " hello world " → "hello world"
// Also collapse multiple internal spaces to one
const cleaned = str.trim().replace(/s+/g, ' ');
// " hello world " → "hello world"
// Remove ALL spaces (not recommended — loses word boundaries)
const noSpaces = str.replace(/s/g, '');
// "hello world" → "helloworld"
// Trim each line in a multiline string
const cleanedLines = str
.split('
')
.map(line => line.trim())
.join('
');
// Remove blank lines too
const noBlankLines = str
.split('
')
.map(line => line.trim())
.filter(line => line.length > 0)
.join('
');# Remove leading/trailing whitespace
cleaned = s.strip()
# " hello world " → "hello world"
# Trim and collapse internal spaces
import re
cleaned = re.sub(r's+', ' ', s).strip()
# " hello world " → "hello world"
# Strip each line in a multiline string
lines = [line.strip() for line in s.splitlines()]
cleaned = '
'.join(line for line in lines if line)Fix spaces with one click
How to Convert String to Lowercase or Uppercase
Case mismatch is a common source of bugs — comparing user-entered email addresses without normalizing case, matching API keys that are case-sensitive, or generating CSS class names with inconsistent capitalization.
// JavaScript
const lower = str.toLowerCase(); // "Hello World" → "hello world"
const upper = str.toUpperCase(); // "Hello World" → "HELLO WORLD"
const title = str.replace(/w/g, c => c.toUpperCase()); // Title Case
// Python
lower = s.lower() # "Hello World" → "hello world"
upper = s.upper() # "Hello World" → "HELLO WORLD"
title = s.title() # "hello world" → "Hello World"
sentence = s.capitalize() # "hello world" → "Hello world"
// JavaScript — safe email comparison
const emailsMatch = userInput.toLowerCase() === storedEmail.toLowerCase();
// Python — safe string key lookup
if user_input.lower() == stored_value.lower():
passAPI key comparison failing due to case
Case-sensitive comparison
// User types "MYAPIKEY123" but comparison expects "myapikey123"
if (userInput === storedKey) {
// Will fail — case sensitive comparison
}Normalized comparison
// Always normalize case before comparison
if (userInput.toLowerCase() === storedKey.toLowerCase()) {
// Works regardless of capitalization
}
// Better: normalize at input time (on the way in)
const normalizedKey = userInput.trim().toLowerCase();String Utilities
The String Utilities tool converts the entire text to UPPERCASE, lowercase, Title Case, or Sentence case in one click — no code needed. It also handles camelCase, PascalCase, and snake_case conversion simultaneously.
How to Replace Text in a String Online
Find-and-replace with regex is one of the most useful string operations for developers — cleaning up log output, reformatting data, sanitizing user input, or bulk-renaming patterns across a text block.
Paste your text into String Utilities
Go to unblockdevs.com/string-utilities and paste the text you want to modify into the input box.
Go to the Transform tab
Click "Transform" in the tab bar. Scroll to the Find & Replace section.
Enter your find and replace values
Type the text (or regex pattern) you want to find in the "Find" field and the replacement in the "Replace" field.
Enable regex mode if needed
Toggle "Use Regex" for pattern-based replacements. Supports standard JavaScript regex syntax including lookaheads and capture groups.
Copy the result
The preview updates in real time. Click the copy button to copy the cleaned text.
// Replace all occurrences (use replaceAll or /g flag)
const result = str.replace(/old/g, 'new'); // All occurrences
const result = str.replaceAll('old', 'new'); // ES2021+
// Remove all digits
const noDigits = str.replace(/d/g, '');
// Remove all special characters (keep letters, numbers, spaces)
const clean = str.replace(/[^a-zA-Z0-9s]/g, '');
// Replace multiple spaces with single space
const collapsed = str.replace(/s+/g, ' ');
// Remove HTML tags
const noHtml = str.replace(/<[^>]*>/g, '');
// Replace line endings (normalize CRLF to LF)
const normalized = str.replace(/
/g, '
');
// Extract only the numbers from a string
const numbers = str.replace(/[^d.,-]/g, '');str.replace() only replaces the first match
Only replaces first match
// replace() without /g flag only replaces the FIRST match
const result = "aaa".replace("a", "b");
// → "baa" (only first 'a' replaced)Replaces all matches
// Use replaceAll() or /g regex flag for all matches
const result = "aaa".replaceAll("a", "b");
// → "bbb"
// Or regex with global flag:
const result = "aaa".replace(/a/g, "b");
// → "bbb"How to Split a String into Parts Online
Splitting strings is fundamental — breaking a CSV row into values, splitting a path into segments, parsing a comma-separated list of IDs, or splitting a JWT token at the dots. The String Utilities Bulk Mode uses the same separator concept for processing lists.
// JavaScript split()
"a,b,c".split(",") // → ["a", "b", "c"]
"hello world".split(" ") // → ["hello", "world"]
"a b c".split(/s+/) // → ["a", "b", "c"] (handles multiple spaces)
"abc".split("") // → ["a", "b", "c"] (split into chars)
// Limit number of splits
"a,b,c,d".split(",", 2) // → ["a", "b"] (first 2 only)
// Python split()
"a,b,c".split(",") # → ["a", "b", "c"]
"a b c".split() # → ["a", "b", "c"] (splits on any whitespace)
"a,b,c,d".split(",", 2) # → ["a", "b", "c,d"] (max 2 splits)
// Split a JWT token
const [header, payload, signature] = jwtToken.split(".");
const decoded = JSON.parse(atob(payload));Paste your list into String Utilities
The tool accepts newline-separated, comma-separated, or pipe-separated lists for bulk conversion.
Select the separator from the dropdown
Choose newline (default), comma, pipe, tab, or enter a custom delimiter.
See each item individually
The tool splits the input and shows each item separately in the output table for individual operations.
Apply operations to all items
Any transform (trim, case convert, encode) is applied to every item in the list simultaneously.
How to Clean a String Before Sending to an API
User input must be cleaned before it reaches an API or database. Raw strings from form fields, clipboard paste, or file uploads often contain invisible characters, encoding issues, and formatting quirks that cause failures downstream.
Trim whitespace
Remove leading/trailing spaces. A token with a trailing newline will return 401 — the most common invisible bug.
Remove special characters
Strip characters not valid in your data format. Use allow-list regex: /[^a-zA-Z0-9_-]/g for slugs.
URL encode
Encode query parameter values before appending to URLs. Use encodeURIComponent() — not encodeURI().
Escape HTML entities
Convert &, <, >, ", ' to their HTML entity equivalents before rendering user content in HTML.
Collapse multiple spaces
Replace consecutive whitespace with a single space — prevents injection of visual formatting tricks.
Case normalize
Lowercase emails and usernames before storing or comparing — prevents duplicate accounts and comparison bugs.
Remove empty lines
Strip blank lines from multiline inputs before JSON serialization or database storage.
Deduplicate lines
Remove duplicate values from lists — prevents sending duplicate IDs to APIs or inserting duplicate rows.
Raw user input in API call vs properly cleaned input
Raw user input — dangerous
// Sending raw user input directly — spaces, encoding issues, injection risk
const response = await fetch(`/api/search?q=${userInput}`);
// If userInput = "hello world & <script>" → URL and injection problemsCleaned and encoded — safe
// Clean and encode before sending
const cleaned = userInput.trim().toLowerCase();
const encoded = encodeURIComponent(cleaned);
const response = await fetch(`/api/search?q=${encoded}`);
// "hello world & <script>" → "hello%20world%20%26%20%3Cscript%3E"
// Safe: spaces encoded, special chars encoded, leading/trailing spaces removedHow to Remove Special Characters from a String
Special characters cause failures in SQL queries, regex patterns, JSON strings, and HTML content. The right approach depends on whether you want to remove them, escape them, or encode them — each has a different use case.
// Remove all special chars — keep only letters, numbers, spaces
const clean = str.replace(/[^a-zA-Z0-9s]/g, '');
// Remove special chars — keep hyphens and underscores (for slugs/IDs)
const slug = str.replace(/[^a-zA-Z0-9-_]/g, '');
// Escape for use in a regex pattern (when user input becomes a regex)
const escaped = str.replace(/[.*+?^${}()|[]\]/g, '\$&');
// Escape HTML entities (prevent XSS)
const escapeHtml = (s) => s
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
// Python — remove non-ASCII chars
import re
clean = re.sub(r'[^ -]+', '', s) # Remove non-ASCII
# Python — keep only alphanumeric
clean = re.sub(r'[^a-zA-Z0-9]', '', s)In the String Utilities tool, the Transform tab provides dedicated buttons for escaping HTML entities, escaping for regex, URL-encoding, and removing non-ASCII characters — no regex knowledge required.