Remove Spaces from a String in TypeScript

In this tutorial, I will explain how to remove spaces from a string in TypeScript with detailed examples. Whether working on a web application or developing a software solution for a tech company, you will get this requirement. Let me show you various methods to remove spaces from strings in TypeScript.

There are various reasons you need to remove spaces from strings in TypeScript, such as:

  • Data Validation: Ensuring user input is clean and consistent.
  • Formatting: Preparing strings for storage or display.
  • Performance: Reducing unnecessary characters can improve processing speed.

Using trim() to Remove Leading and Trailing Spaces

The best way to remove spaces from the beginning and end of a string in TypeScript is by using the trim() method. This method is easy and does not alter the original string.

Example:

Let me show you an example.

let address: string = "  1600 Pennsylvania Avenue NW  ";
let trimmedAddress: string = address.trim();
console.log(trimmedAddress); // Output: "1600 Pennsylvania Avenue NW"

In this example, the trim() method removes the leading and trailing spaces from the address string.

Here is the exact output in the screenshot below;

Remove specified number of times in python

Check out How to Check if a String is Empty in TypeScript?

Remove All Spaces Using replace()

If you need to remove all spaces within a string in TypeScript, the replace() method with a regular expression is the way to go. You can use this method to target specific characters for removal.

Let me show you an example.

Example:

Here is an example with the complete code.

let fullName: string = "John  F.  Kennedy";
let noSpacesName: string = fullName.replace(/\s/g, "");
console.log(noSpacesName); // Output: "JohnF.Kennedy"

Here, the regular expression \s matches any whitespace character, and the g flag ensures that all occurrences are replaced.

Here is the exact output in the screenshot below:

TypeScript Remove Spaces from a String

Read Replace All Occurrences of a Substring in a String in TypeScript

Using replaceAll() for Simplicity

Introduced in ECMAScript 2021, the replaceAll() method simplifies the process of replacing all instances of a substring in TypeScript.

Example:

Here is an example.

let city: string = "San Francisco";
let noSpacesCity: string = city.replaceAll(" ", "");
console.log(noSpacesCity); // Output: "SanFrancisco"

This method is more readable and concise compared to using regular expressions.

Check out Check if a String is in an Enum in TypeScript

Combine trim() and replace() for Comprehensive Space Removal

Sometimes, you might need to remove spaces from both ends of a string and within the string itself. For these scenarios, you can combine trim() and replace() to achieve this.

Example:

Here is an example.

let sentence: string = "  The quick brown fox jumps over the lazy dog  ";
let cleanedSentence: string = sentence.trim().replace(/\s+/g, " ");
console.log(cleanedSentence); // Output: "The quick brown fox jumps over the lazy dog"

In this example, trim() removes the leading and trailing spaces, while replace(/\s+/g, " ") ensures that multiple spaces within the string are reduced to a single space.

Check out Split a String by Comma in TypeScript

Remove Spaces from a String – Real Example

Imagine you are developing a web application for a real estate company in Los Angeles. Users frequently input addresses with inconsistent spacing. You need to clean these inputs before storing them in the database.

Example:

Here is an example.

function cleanAddressInput(address: string): string {
    return address.trim().replace(/\s+/g, " ");
}

let rawAddress: string = "  1234   Elm Street   ";
let cleanedAddress: string = cleanAddressInput(rawAddress);
console.log(cleanedAddress); // Output: "1234 Elm Street"

This function ensures that the address is free of unnecessary spaces, making it ready for storage or further processing.

You can see the output in the screenshot below:

How to Remove Spaces from a String in TypeScript

Read Convert an Array to a String in TypeScript

Handle Usernames: Ensuring Consistency

For consistency and ease of use, usernames must be free of spaces in a social media application based in Austin, Texas.

Example:

Here is an example.

function formatUsername(username: string): string {
    return username.trim().replace(/\s/g, "");
}

let rawUsername: string = "  jane_doe  ";
let formattedUsername: string = formatUsername(rawUsername);
console.log(formattedUsername); // Output: "jane_doe"

This function ensures that the username is clean and consistent, improving user experience and data integrity.

Check out Convert Boolean to String in TypeScript

Advanced Techniques: Using split() and join()

For more complex scenarios, you might need to split a string into an array of words and then join them back together without spaces.

Example:

Here is an example and the complete code.

let slogan: string = "E Pluribus Unum";
let words: string[] = slogan.split(" ");
let noSpacesSlogan: string = words.join("");
console.log(noSpacesSlogan); // Output: "EPluribusUnum"

This method gives you more control over how spaces are handled and can be helpful for more advanced string manipulations.

Conclusion

In this tutorial, I have explained how to remove spaces from strings in TypeScript using various methods, such as using trim(), replace(), replaceAll(), or a combination of these methods, etc.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.