JavaScript

Trim whitespace from the edges of a string

Use trim to remove leading and trailing whitespace while preserving whitespace inside a string. This is a common first step for text input, but it should follow the meaning of the field.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const raw = "  one  two\n";
const cleaned = raw.trim();
console.log(JSON.stringify(cleaned));
console.log(raw.length > cleaned.length);

How it works

Trim returns a new string because JavaScript strings are immutable. The two spaces between one and two remain. Wrapping the output with JSON.stringify makes invisible leading, trailing, or embedded characters easier to inspect during debugging.

Limits and mistakes

Do not trim passwords or whitespace-sensitive source text without an explicit requirement. Trimming is not HTML sanitization and does not remove all invisible Unicode characters. Validate length and content after any intentional normalization.

Check the result

Expect "one two" and true. Try tabs, an all-whitespace input, and significant spaces inside a value. An empty result may need a separate required-field error.

Sources

Reference documentation for the behavior used in this guide: