Removing extra whitespace
Text from forms, files and copy-and-paste often has spaces, tabs or line breaks at the edges. Other languages call the fix "strip"; in TypeScript, as in JavaScript, the method is called trim:
s.trim() // removes leading and trailing whitespace
s.trimStart() // removes only leading whitespace
s.trimEnd() // removes only trailing whitespace
Leading means at the start of the string, and trailing means at the end. Here is each method on a string with two spaces on both sides. The brackets in the output make the spaces visible:
const s: string = " hello ";
console.log(`[${s.trim()}]`); // [hello]
console.log(`[${s.trimStart()}]`); // [hello ]
console.log(`[${s.trimEnd()}]`); // [ hello]
All three return a new string. The original keeps its spaces, because strings can't be changed in place.
The exercise
The starting code defines the padded string:
const s: string = " hello ";
The task is to build a const named result, typed string, that holds the trimmed text.
- Below
s, declareconst result: string. - Call
s.trim()to remove the whitespace from both ends. - Assign the returned string to
result.
The finished code:
const s: string = " hello ";
const result: string = s.trim();
Now result is "hello", five characters long, while s still has its nine characters.
What counts as whitespace
The methods remove more than the space character. Tabs, line breaks (\n and \r) and other Unicode space characters, such as the non-breaking space, are removed too:
const raw: string = "\t\n hi \r\n";
console.log(`[${raw.trim()}]`); // [hi]
That makes trim a good first step when you read a line of input and want to compare it with something.
Gotchas
- Only the edges are touched. Spaces inside the text stay:
"a b".trim()is still"a b". To change spaces inside, usereplaceAllor split the string and join it again. - Ignoring the result. A line such as
t.trim();by itself changes nothing. Keep the new string:t = t.trim();needs a variable declared withlet. - A string of only whitespace becomes empty.
" ".trim()is"", whose length is 0. That is a handy test for "was anything typed?":input.trim().length === 0. - The names differ between languages. There is no
stripmethod on a TypeScript string. Callings.strip()is a compile error, and at run time it would throw because no such method exists. - Trim before you compare or split.
"yes "is not equal to"yes", and" a b ".split(" ")gives empty pieces at both ends. Callingtrim()first avoids both.
Because every method returns a string, they chain naturally. For example, input.trim().toLowerCase() cleans up spacing and letter case in one expression.
A practical example
Suppose a program receives an answer typed by a person and must decide whether it says yes. People add stray spaces and capital letters without noticing, so comparing the raw text fails:
const answer: string = " Yes ";
console.log(answer === "yes"); // false
console.log(answer.trim().toLowerCase() === "yes"); // true
The first comparison is false for two reasons: the spaces and the capital Y. Trimming handles the first, and toLowerCase() handles the second. Cleaning the input once, before any comparison, keeps the rest of the program simple. It also keeps the original text available, since neither method changes answer.
The directional versions are rarer, but they matter when one side carries meaning. Leading spaces can be indentation that you want to keep while you drop a trailing newline, and trimEnd() does exactly that. Use trimStart() when only the beginning is untidy.
When you aren't sure whether a value needs trimming, calling trim() anyway is safe. On a string without edge whitespace it just returns an equal string, so there is no harm in cleaning input that was already clean.
Key takeaways
trim()removes whitespace from both ends of a string,trimStart()from the start only, andtrimEnd()from the end only.- Whitespace includes spaces, tabs and line breaks, but only at the edges of the string.
- The methods return a new string; the original stays the same.
- There is no
stripin TypeScript: the method istrim.