Fri Nov 19 2021·2 min read
Photo by Charlie Hang
To remove the underscores from a string, call the
replaceAll() method on the
string, passing it an underscore as the first parameter, and an empty string as
the second, e.g.
replaceAll('_', ''). The
replaceAll method will return a
new string, where all underscores are removed.
const str = 'a_b_c'; // ✅ Remove all underscores const result1 = str.replaceAll('_', ''); console.log(result1); // 👉️ "abc" // ✅ Remove all underscores using regex const result2 = str.replace(/_/g, ''); console.log(result2); // 👉️ "abc" // ✅ Remove only first underscore const result3 = str.replace(/_/, ''); console.log(result3); // 👉️ "ab_c"
The two parameters we passed to the String.replaceAll method are:
By replacing each underscore with an empty string we practically remove the underscores from the string.
Alternatively, you can use the String.replace method.
To remove all the underscores from a string, call the
replace() method on
the string, passing it the following regular expression -
/_/g, and replace
each match of the regular expression with an empty string, e.g.
const str = 'a_b_c'; const result2 = str.replace(/_/g, ''); console.log(result2); // 👉️ "abc"
The first parameter we passed to the
replace method is a regular expression,
and the second - the replacement for each match.
The forward slashes
/ / mark the beginning and end of the regular expression.
Our regular expression consists of a single underscore.
g(global) flag because we want to match all occurrences of an underscore in the string, and not just the first occurrence.
Because we want to remove the underscores from the string, we replace each underscore with an empty string.
replaceis supported in Internet Explorer, whereas
If you only want to replace the first occurrence of an underscore character, you
simply have to remove the
g (global) flag from the regular expression.
const str = 'a_b_c'; const result3 = str.replace(/_/, ''); console.log(result3); // 👉️ "ab_c"
By default, the
replace method replaces the first occurrence of the match
characters with the provided replacement.
By removing the
g (global) flag, we only match the first underscore in the