Sometimes, we want to remove characters from a string with JavaScript.
In this article, we’ll look at how to remove characters from a string with JavaScript.
How to remove characters from a string with JavaScript?
To remove characters from a string with JavaScript, we use the string replace
method.
For instance, we write
const str = "foo bar baz";
const newStr = str.replace(/ba/gi, "");
to call str.replace
with a regex that matches the pattern we want to remove.
And we replace all matches with empty strings.
The g
flag makes replace
replace all matches.
i
matches it find matches in a case-insensitive manner.
Conclusion
To remove characters from a string with JavaScript, we use the string replace
method.