How to Replace Spaces with Underscores in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 04 20211 min read

banner

Photo by Jake Melara

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
// Not Supported in IE 6-11 const str = 'a very long string'; const strUnderscores = str.replaceAll(' ', '_'); console.log(strUnderscores); // ๐Ÿ‘‰๏ธ a_very_long_string

We called the String.replaceAll method with 2 parameters - the string to be replaced and the replacer string.

The String.replaceAll method returns a new string with the matches replaced, it doesn't change the original string. Strings are immutable in JavaScript.

The String.replaceAll method is not supported in Internet Explorer. If you have to support the browser, use the String.replace method instead.

index.js
// Supported in IE 6-11 const str = 'a very long string'; const strUnderscores = str.replace(/ /g, '_'); console.log(strUnderscores); // ๐Ÿ‘‰๏ธ a_very_long_string

In the code snippet, we use the String.replace method, passing it a regular expression as the first parameter and a replacer string as the second.

The regular expression / / matches a whitespace character.

We have added the g (global) flag to the regex, which makes the regular expression match all whitespace characters in the string, instead of just the first one.

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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee