Skip to main content

How to Replace Spaces with Underscores in a JavaScript String

Replacing spaces with underscores is a very common string manipulation task, often used to create URL-friendly "slugs," safe filenames, or formatted identifiers. Modern JavaScript provides a simple and highly readable method for this: String.prototype.replaceAll().

This guide will teach you how to use replaceAll() as the primary method for this task. We will also cover the more powerful replace() method with regular expressions for handling more complex whitespace scenarios, such as replacing multiple spaces with a single underscore.

The replaceAll() method is the most direct and modern way to replace every occurrence of a specific character in a string. It is easy to read and clearly communicates your intent.

For example, you have a string with spaces and want to replace each one with an underscore.

// Problem: Replace the spaces in this string.
const originalString = 'my example string';

The solution is to provide the space character (' ') as the first argument and the underscore character ('_') as the second.

const originalString = 'my example string';

const newString = originalString.replaceAll(' ', '_');

console.log(newString);

Output:

my_example_string
note

Important: Strings are immutable in JavaScript. The replaceAll() method does not modify the original string; it returns a new string with the replacements made.

How to Handle Leading/Trailing Spaces

If your string has leading or trailing spaces, replaceAll() will convert them to underscores as well. To avoid this, you can use the trim() method first.

const messyString = '  leading and trailing spaces  ';

// This will have leading and trailing underscores
const withExtraUnderscores = messyString.replaceAll(' ', '_');
console.log(withExtraUnderscores); // __leading_and_trailing_spaces__

// Trim first to avoid this
const trimmedAndReplaced = messyString.trim().replaceAll(' ', '_');
console.log(trimmedAndReplaced); // leading_and_trailing_spaces

Output:

__leading_and_trailing_spaces__
leading_and_trailing_spaces

Handling Multiple Spaces with a Regular Expression

Sometimes, your string might have inconsistent spacing with multiple spaces between words. If the goal is to replace any block of one or more spaces with a single underscore, you must use the replace() method with a regular expression.

For example, the string has multiple spaces between words. How to convert any block of spaces into a single underscore?

// Problem: Convert any block of spaces into a single underscore.
const messyString = 'my example string';

The solution is to use a regular expression that matches one or more space characters globally.

const messyString = 'my   example    string';

// The regex / +/g matches one or more spaces, globally.
const newString = messyString.replace(/ +/g, '_');

console.log(newString);

Output:

my_example_string

How it works:

  • : The pattern starts with a literal space character.
  • +: This is a quantifier that means "one or more times." So, + matches any continuous block of spaces.
  • /g: The global flag ensures that replace() finds all blocks of spaces, not just the first one.

An Alternative (Verbose) Method: split() and join()

Before replaceAll() was widely available, a common technique was to split() the string by spaces and then join() the resulting array with underscores.

const originalString = 'my example string';

// 1. Split the string into an array of words.
const words = originalString.split(' ');
console.log(words);

// 2. Join the array back into a string with an underscore.
const newString = words.join('_');

console.log(newString);

Output:

['my', 'example', 'string']
my_example_string
note

While this works well, it is less direct and readable than replaceAll(). It also has the side effect of automatically handling multiple spaces, which may or may not be the desired behavior.

Conclusion

JavaScript offers several powerful ways to replace spaces with underscores, but the modern solution is the clearest for most cases.

  • To replace every single space with an underscore, the string.replaceAll(' ', '_') method is the recommended best practice. It is explicit and highly readable.
  • To replace any block of one or more spaces with a single underscore, you must use a regular expression: string.replace(/ +/g, '_').
  • The string.split(' ').join('_') method is a functional alternative but is generally less direct than replaceAll().