Ora

How do you replace all spaces in JavaScript?

Published in JavaScript String Manipulation 4 mins read

In JavaScript, you can replace all spaces in a string using either the replaceAll() method or the replace() method combined with a global regular expression. Both methods return a new string with the spaces replaced, leaving the original string untouched.

1. Using String.prototype.replaceAll()

The replaceAll() method, introduced in ECMAScript 2021 (ES12), is the most direct and modern way to replace all instances of a specific substring within a string.

  • How it Works: The String.replaceAll() method returns a new string where every occurrence of a specified pattern is replaced by a given replacement string. The first argument is the pattern (the character or string you want to find), and the second argument is the replacement (what you want to substitute it with).
  • Syntax: yourString.replaceAll(pattern, replacement)

Example: Removing All Spaces

To simply remove all spaces, you replace them with an empty string:

const originalString = "Hello world, this is a test string.";
const stringWithoutSpaces = originalString.replaceAll(' ', '');
console.log(stringWithoutSpaces);
// Output: "Helloworld,thisisateststring."

In this example, originalString.replaceAll(' ', '') removes all the spaces by replacing each space character (' ') with an empty string ('').

Key Advantages of replaceAll():

  • Simplicity: No need for complex regular expressions for basic string replacements.
  • Clarity: Its name clearly indicates its global replacement behavior, making code easier to read.
  • Direct: Specifically designed for replacing all occurrences of a string literal.

For more in-depth information, you can refer to the MDN Web Docs on String.prototype.replaceAll().

2. Using String.prototype.replace() with a Global Regular Expression

The replace() method is a long-standing and widely supported JavaScript string method. While it typically replaces only the first occurrence of a string or regex match, you can make it replace all occurrences by providing a regular expression with the global flag (g).

  • How it Works: When replace() is used with a regular expression that includes the g flag (e.g., /pattern/g), it searches for all matches of that pattern throughout the string and replaces each one with the specified replacement.
  • Syntax: yourString.replace(/pattern/g, replacement)

Example: Removing All Spaces with a Global Regex

To remove all literal spaces:

const originalString = "Another example string with spaces.";
const stringWithoutSpacesRegex = originalString.replace(/ /g, '');
console.log(stringWithoutSpacesRegex);
// Output: "Anotherexamplestringwithspaces."

Replacing All Whitespace Characters (\s)

If you need to replace all types of whitespace characters—including spaces, tabs (\t), newlines (\n), carriage returns (\r), form feeds (\f), and vertical tabs (\v)—you can use the \s character class in your regular expression:

const multiLineString = "  Hello \n  world \t again.  ";
const noWhitespace = multiLineString.replace(/\s/g, '');
console.log(noWhitespace);
// Output: "Helloworldagain."

Key Advantages of replace() with Regex:

  • Browser Compatibility: Excellent, widely supported across all modern and older browsers.
  • Flexibility: Regular expressions offer powerful pattern matching capabilities for more complex scenarios beyond simple spaces (e.g., replacing multiple spaces with one, removing leading/trailing spaces, or targeting specific character sets).
  • Specificity: You can define precisely what type of "space" or whitespace to target.

For further details, consult the MDN Web Docs on String.prototype.replace().

Comparing replaceAll() and replace() with Regex

Choosing between these two methods often depends on your specific requirements, the complexity of the pattern, and your target browser support.

Feature replaceAll() (ES2021) replace() with Global Regex (/g)
Pattern Type String or Regular Expression Regular Expression only
Global Replace Default for string patterns Requires the g flag for regex
Simplicity Simpler for literal string replacements More powerful for complex pattern matching
Browser Support Newer standard (consider polyfills for older browsers) Excellent, long-standing support
Use Case Best for direct, exact string replacements Ideal for advanced, flexible pattern matching

Practical Applications and Examples

Beyond simply removing spaces, these methods are invaluable for various string manipulation tasks:

  • Creating URL Slugs: Replacing spaces with hyphens and converting to lowercase.
    const articleTitle = "My Awesome Blog Post Title";
    const slug = articleTitle.replaceAll(' ', '-').toLowerCase();
    console.log(slug); // Output: "my-awesome-blog-post-title"
  • Standardizing Input: Replacing multiple consecutive spaces with a single space.
    const messyUserInput = "  Hello    world   from    JavaScript.  ";
    const cleanedInput = messyUserInput.replace(/\s+/g, ' ').trim(); // \s+ matches one or more whitespace characters
    console.log(cleanedInput); // Output: "Hello world from JavaScript."
  • Cleaning Data: Removing other specific characters or symbols globally.
    const rawProductId = "ITEM_CODE-ABC_123";
    const cleanProductId = rawProductId.replaceAll('_', '').replaceAll('-', '');
    console.log(cleanProductId); // Output: "ITEMCODEABC123"

By utilizing these powerful JavaScript string methods, you can efficiently clean, format, and manipulate text data to suit your application's needs.