Tue Oct 26 2021·2 min read
Photo by Toa Heftiba
replace() method to replace the first occurrence of a character in a
string. The method takes a regular expression and a replacement string as
parameters and returns a new string with one or more matches replaced.
const str = 'hello world'; const replaceFirst = str.replace(/l/, '_'); console.log(replaceFirst); // 👉️ he_lo world const replaceAll = str.replace(/l/g, '_'); console.log(replaceAll); // 👉️ he__o wor_d
We used the
method to replace the first occurrence of the
l character in the string
g(global) flag after the regular expression.
The forward slashes
/ / mark the beginning and end of the regular expression.
The second parameter the
replace method takes is the replacement string.
In our example, we replaced the
l character with an underscore
If you ever need help reading or writing a regular expression, bookmark this regex cheatsheet from MDN. It's by far the best one out there.
If you need to match the first occurrence of a character in a case-insensitive
manner, add the
i flag at the end of the regex.
const str = 'HELLO WORLD'; const replaceFirst = str.replace(/l/i, '_'); console.log(replaceFirst); // 👉️ HE_LO WORLD const replaceAll = str.replace(/l/gi, '_'); console.log(replaceAll); // 👉️ HE__O WOR_D
In this example, we used the
i flag to perform a case insensitive search for
l character in the string and replace it with an underscore.
I'll send you 1 email a week with links to all of the articles I've written that week