Borislav Hadzhiev
Mon Oct 04 2021·2 min read
Photo by Jake Melara
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.
// 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.
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.
// 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.
g
flag, only the first occurrence of a whitespace character would get replaced with an underscore.