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();
}Report a problem with this exampleOpens a pre-filled issue on GitHub.