Mon Oct 04 2021·1 min read
Photo by Jake Melara
String.replaceAll method to replace all spaces with underscores in a
string.replaceAll(' ', '_'). The
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 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
gflag, only the first occurrence of a whitespace character would get replaced with an underscore.
I'll send you 1 email a week with links to all of the articles I've written that week