Whitespace Normalizer for User Input
Trim, collapse and optionally preserve line breaks while removing zero-width characters that break search and comparison.
Code
export function normalizeWhitespace(text, options = {}) {
if (typeof text !== "string") throw new TypeError("text must be a string");
const preserveNewlines = options.preserveNewlines === true;
const withoutInvisible = text.replace(/[\u200B-\u200D\uFEFF]/g, "");
if (preserveNewlines) {
return withoutInvisible
.split(/\r\n|\r|\n/)
.map((line) => line.replace(/[ \t\f\v]+/g, " ").trim())
.join("\n")
.trim();
}
return withoutInvisible.replace(/\s+/g, " ").trim();
}Inside the snippet
Whitespace Normalizer for User Input comes down to the function normalizeWhitespace.
TypeError is the guard’s signal — thrown at the branch, before any partial work happens.
What to watch for
- The guard
typeof text !== "string"short-circuits the flow with an earlythrowwhen its condition holds.
Putting it to use
The main signature reads export function normalizeWhitespace(text, options = {})
Callers only need normalizeWhitespace — everything else stays internal.
Core lines
if (typeof text !== "string") throw new TypeError("text must be a string");
return withoutInvisible.replace(/\s+/g, " ").trim();
.map((line) => line.replace(/[ \t\f\v]+/g, " ").trim())
.join("\n")
.trim();
Interactive Tools for This Topic
Whitespace NormalizerTrim line edges, collapse repeated spaces, convert tabs, and remove blank lines from text without changing its words or punctuation.Diff Ignoring WhitespaceCompare two blocks of text line by line and separate true differences from lines that differ only in spacing, indentation, or line endings.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.User-Agent ParserParse a browser User-Agent string into browser, rendering engine, operating system, device type, and bot flag.
FAQ
- How are precondition violations signaled?
- `TypeError` is raised at the guard (`typeof text !== "string"`), so invalid state never reaches the main logic.
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `normalizeWhitespace` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.