Whitespace Normalizer for User Input

Trim, collapse and optionally preserve line breaks while removing zero-width characters that break search and comparison.

JavascriptData Integrity

Code

javascriptsnippet
13 lines
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 early throw when 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

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.