Regex patterns/Text & extraction
Trim leading and trailing whitespace
Two anchored alternatives in one pass — the classic trim, per line.
/^\s+|\s+$/gmThe problem
Strip the spaces and tabs at the start and end of every line, leaving the text between them alone.
How it reads
Follow the line from left to right — every path you can trace is a string this pattern matches.
^\s+|\s+$Any one of these alternatives:^\s+In order:^The start of the text (or of a line with the m flag)\s+Whitespace, one or more times, as many as possible\s+$In order:\s+Whitespace, one or more times, as many as possible$The end of the text (or of a line with the m flag)
Matches
- padded
- trailing
Does not match
- clean
- inner space
Where it bites
- Without the g flag you replace only the leading whitespace; both alternatives need to fire.
- The m flag is what makes ^ and $ mean "each line" rather than "the whole string".
- For a single string in JavaScript, value.trim() is faster and clearer. This earns its place when trimming every line of a block at once.