How to Replace Spaces with Underscores in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 1, 2024
4 min

banner

# Replacing Spaces with Underscores in JavaScript

Use the String.replaceAll() method to replace all spaces with underscores in a JavaScript string, e.g. string.replaceAll(' ', '_').

The replaceAll method returns a new string with all whitespace characters replaced by underscores.

index.js
const str = 'bobby hadz com'; const replaced = str.replaceAll(' ', '_'); console.log(replaced); // ๐Ÿ‘‰๏ธ bobby_hadz_com

replacing spaces with underscores

The code for this article is available on GitHub

The String.replaceAll() method returns a new string with all matches of a pattern replaced by the provided replacement.

The method takes the following parameters:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

The String.replaceAll() method returns a new string with the matches of the pattern replaced. The method doesn't change the original string.

Strings are immutable in JavaScript.

If you have to do this often, define a reusable function.

index.js
function replaceSpaceWithUnderscore(str) { return str.replaceAll(' ', '_'); } const str = 'bobby hadz com'; const result = replaceSpaceWithUnderscore(str); console.log(result); // ๐Ÿ‘‰๏ธ bobby_hadz_com

defining reusable function

The function takes a string as a parameter, replaces all spaces with underscores in the string and returns the result.

If your string has leading and trailing spaces, you'd get leading and trailing underscores.

index.js
const str = ' bobby hadz com '; const result = str.replaceAll(' ', '_'); console.log(result); // ๐Ÿ‘‰๏ธ _bobby_hadz_com_

You can use the trim() method to remove the leading and trailing spaces before calling replaceAll().

index.js
const str = ' bobby hadz com '; const result = str.trim().replaceAll(' ', '_'); console.log(result); // ๐Ÿ‘‰๏ธ bobby_hadz_com

# Replace spaces with underscores in JavaScript using String.replace()

Alternatively, you can use the String.replace() method.

index.js
const str = 'bobby hadz com'; const strUnderscores = str.replace(/ /g, '_'); console.log(strUnderscores); // ๐Ÿ‘‰๏ธ bobby_hadz_com

replace spaces with underscores using string replace

The code for this article is available on GitHub

If you need to replace one or more spaces with a single underscore, use a plus +.

index.js
const str = 'bobby hadz com'; const strUnderscores = str.replace(/ +/g, '_'); console.log(strUnderscores); // ๐Ÿ‘‰๏ธ bobby_hadz_com

The plus + character matches the preceding item (the space) one or more times.

The String.replace() method returns a new string with one, some, or all matches of a regular expression replaced with the provided replacement.

The method takes the following parameters:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

The first argument we passed to the replace() method is a regular expression.

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

In our regular expression, we have a single space.

index.js
const str = 'bobby hadz com'; const strUnderscores = str.replace(/ /g, '_'); console.log(strUnderscores); // ๐Ÿ‘‰๏ธ bobby_hadz_com

We added the g (global) flag to the regex, which makes the regular expression match all spaces in the string and not just the first occurrence.

# Replace the first occurrence of a space with an underscore

If you were to remove the g flag, only the first occurrence of a space would get replaced with an underscore.

index.js
const str = 'bobby hadz com'; const strUnderscores = str.replace(/ /, '_'); console.log(strUnderscores); // ๐Ÿ‘‰๏ธ bobby_hadz com

replace first occurrence of space with underscore

The code for this article is available on GitHub

The code sample doesn't use the g flag, so only the first space in the string is replaced by an underscore.

# Replace all whitespace characters with underscores

If you need to replace all whitespace characters with underscores, use the \s special character.

index.js
const str = 'bobby\nhadz\tcom abc'; const strUnderscores = str.replace(/\s/g, '_'); console.log(strUnderscores); // ๐Ÿ‘‰๏ธ bobby_hadz_com_abc

replace all whitespace characters with underscores

The \s special character matches spaces, tabs and newlines.

# Replace all spaces with underscores using split() and join()

This is a two-step process:

  1. Use the split() method to split the string on each space.
  2. Use the join() method to join the array with an underscore separator.
index.js
const str = 'bobby hadz com'; const result = str.split(' ').join('_'); console.log(result); // ๐Ÿ‘‰๏ธ bobby_hadz_com
The code for this article is available on GitHub

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

NameDescription
separatorThe pattern describing where each split should occur.
limitAn integer used to specify a limit on the number of substrings to be included in the array.

We split the string on each occurrence of a space.

index.js
const str = 'bobby hadz com'; // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(str.split(' '));

The last step is to join the array with an underscore separator.

The Array.join() method concatenates all of the elements in an array using a separator.

The only argument the Array.join() method takes is a separator - the string used to separate the elements of the array.

index.js
const str = 'bobby hadz com'; const result = str.split(' ').join('_'); console.log(result); // ๐Ÿ‘‰๏ธ bobby_hadz_com

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev