Replace Spaces With Underscores in JavaScript

By James L.

In this guide, we will look at different ways to replace spaces with underscores.

We will use the following methods:

  • Using replace() method
  • Using replaceAll() method
  • Using split() and join() methods

We will dive deeply into each above method, but if you want a quick answer, see the first method and call it a day. So, without further ado let’s get started!

Using replace() method

We can replace spaces with underscores by using the built-in JavaScript method replace(). We have to pass the regular expression / /g as the search value and underscore _ as the replacement method. 

The replace() method returns a new string with all the spaces replaced with underscores.

For example:

var str = "JavaScript is awesome";

var result = str.replace(/ /g, "_");

console.log(result);   // Output: JavaScript_is_awesome

Let’s break down the regular expression /⋮⋮⋮/g

Forward slashes / mark the beginning and end of the regular expression.

⋮⋮⋮ A space character matches a space character. Notice: I have used ⋮⋮⋮ to represent blank space character.

g Global flag g matches all the space characters, not just the first space. If we didn’t have global flag g in the above example, the output would have been “JavaScript_is awesome”. It stops after the first match. 

String with multiple space characters between words

If you have multiple space characters between words, you may want to pass regular expression / +/g as the search value and underscore _ as the replacement value.

For example: 

In the example below, we have multiple space characters between words in string str.

var str = "JavaScript   is awesome";

var result = str.replace(/ /g, "_");
var resultTwo = str.replace(/ +/g, "_");

console.log(result);      // Output: JavaScript___is_awesome
console.log(resultTwo);   // Output: JavaScript_is_awesome

Let’s break down the regular expression /⋮⋮⋮+/g

Forward slashes / mark the beginning and end of the regular expression.

⋮⋮⋮ A space character matches a space character. Notice: I have used ⋮⋮⋮ to represent blank space. 

+ Matches previous character one or more times. In our case, it matches multiple space characters.  /e+/g matches ‘ee’ and ‘e’ in ‘breeze’ while /e/g matches ‘e’, ‘e’, and ‘e’ in ‘breeze’.

g Global flag g matches all the occurrences of the match, not just the first match. In our example, it matches all one or more space characters. /e+/g matches ‘ee’ and ‘e’ in ‘breeze’ while /e+/ matches ‘ee’ in ‘breeze’.

String with leading and trailing space characters

If we have one or more whitespace at the beginning and the end of the string, then we may want to remove the whitespaces at the beginning and the end of the string with the trim() method before replacing whitespaces with underscores.

For example:

var str = "   JavaScript is awesome   ";

var result = str.replace(/ +/g, "_");
var resultTwo = str.trim().replace(/ +/g, "_");

console.log(result);      // Output: _JavaScript_is_awesome_
console.log(resultTwo);   // Output: JavaScript_is_awesome

Replace all whitespaces (space, tab, carriage return, line feed, and form feed)

To replace all whitespaces using the replace() method, we have to pass the regular expression /\s/g as the search value and underscore _ as the replacement value. 

The replace() method returns a new string with all the whitespaces replaced with underscores.

For example:

var str = "JavaScript\nis\tawesome";

var result = str.replace(/\s/g, "_");

console.log(result);   // Output: JavaScript_is_awesome

Let’s break down the regular expression /\s/g

Forward slashes / mark the beginning and the end of the regular expression.

\s Matches all whitespace (space, tab, carriage return, line feed, or form feed).

g Global flag g matches all the occurrences of the match.

String with multiple whitespace characters between words

If you have multiple whitespace characters between words then you may want to pass the regular expression /\s+/g as the search value and an underscore _ as the replacement value.

For example:

var str = "JavaScript\n\n\nis\t\t\tawesome";

var result = str.replace(/\s/g, "_");
var result2 = str.replace(/\s+/g, "_");

console.log(result);   // Output: JavaScript___is___awesome
console.log(result2);  // Output: JavaScript_is_awesome

Let’s break down the regular expression /\s+/g

Forward slashes / mark the beginning and the end of the regular expression.

\s Matches space, tab, carriage return, line feed, or form feed.

+  Matches previous matches one or more times. In the above example /\s+/g matches ‘\n\n\n’ and ‘\t\t\t’ whereas /\s/g would match ‘\t’, ‘\t’, ‘\t’, ‘\n’, ‘\n’, and ‘\n’ individually.

g Global flag g finds all matches.

Using replaceAll() method

To replace spaces with underscores using the replaceAll() method, we have to pass the regular expression / /g as the search value and underscore _ as the replacement value. The replaceAll() method returns a new string with all the spaces replaced with underscores.

The replaceAll() method replaces all the matches whereas the replace() method only replaces the first match.

NOTE: We can use replace() and replaceAll() methods interchangeably if we are passing regular expression as the search value with a global flag g. Also, note that a global flag g is compulsory for the replaceAll() method.

For example:

var str = "JavaScript is awesome";

var result = str.replaceAll(/ /g, "_");
var result2 = str.replace(/ /g, "_");
var result3 = str.replace(/ /, "_");

console.log(result);    // Output: JavaScript_is_awesome
console.log(result2);   // Output: JavaScript_is_awesome
console.log(result3);   // Output: JavaScript_is awesome

We can also pass a string with a space character as the search value and an underscore as the replacement value in the replaceAll() method.

For example:

var str = "JavaScript is awesome";

var result = str.replaceAll(" ", "_");

console.log(result);   // Output: JavaScript_is_awesome

Using split() and join() method

To replace spaces with underscores using the split() and join() methods:

  1. First, we split the string into an array of sub-strings at each occurrence of space by passing space as the separator in the split() method.
  2. Second, we join the array of sub-strings together by passing the underscore _ as the separator in the join() method.

For example:

var str = "JavaScript is awesome";

var result = str.split(" ").join("_");

console.log(result);   // Output: JavaScript_is_awesome

Alternatively, we can also pass a regular expression as the separator in the split() method. The benefit of using a regular expression as the separator is we can have complex logic based on our needs.

In the example below, we split the string into an array of substrings at each occurrence of one or more spaces by passing the regular expression / +/ as the separator in the split() method. Then we join the array of substrings by passing the underscore as the separator in the join() method.

var str = "JavaScript   is awesome";
 
var result = str.split(/ /).join("_");
var result2 = str.split(/ +/).join("_");
 
console.log(result);   // Output: JavaScript___is_awesome
console.log(result2);  // Output: JavaScript_is_awesome