Remove all Whitespace from a String in TypeScript

avatar

Borislav Hadzhiev

Thu Mar 10 20222 min read

banner

Photo by Lucas Lenzi

Remove all Whitespace from a String in TypeScript #

Use the replace() method to remove all whitespace from a string in TypeScript, e.g. str.replace(/\s/g, ''). The replace method takes a regular expression and a replacement string as parameters. The method will return a new string with all whitespace removed.

index.ts
const str = ' one two three '; // ✅ Remove all Whitespace const withoutAnyWhitespace = str.replace(/\s/g, ''); console.log(withoutAnyWhitespace); // 👉️ "onetwothree" // ✅ Remove only leading and trailing whitespace const result = str.trim(); console.log(result); // 👉️ "one two three"

We used the replace() method to remove all whitespace from a string.

We passed the following 2 parameters to the String.replace method:

  1. A regular expression we want to match in the string.
  2. The replacement for each match.

The forward slashes / / mark the beginning and end of the regular expression.

The \s metacharacter matches spaces, tabs and newlines.

We use the g (global) flag to specify that we want to match all occurrences of whitespace characters in the string, not just the first occurrence.

The second parameter the replace method takes is the replacement. In our case, we want to replace all whitespace with an empty string (nothing).

Note that the String.replace method does not change the original string, it returns a new string. Strings are immutable in JavaScript (and TypeScript).

If you need to remove only the leading and trailing whitespace from a string, use the String.trim() method.

index.ts
const str = ' one two three '; // ✅ Remove leading and trailing whitespace const result = str.trim(); console.log(result); // 👉️ "one two three"

The trim() method will remove the whitespace from both ends of the string and return a new string.

The method does not modify the original string, it returns a new string.

Use the search field on my Home Page to filter through my more than 1,000 articles.