Replace the First Occurrence of Character in String in JS

avatar

Borislav Hadzhiev

Tue Oct 26 20212 min read

banner

Photo by Toa Heftiba

Replace the First Occurrence of Character in String #

Use the 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.

index.js
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 String.replace method to replace the first occurrence of the l character in the string hello world.

The difference between replacing the first match of a regex in a string and replacing all matches is specifying the 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 _.

The replace method does not change the contents of the original string, it returns a new string. Strings are immutable in JavaScript.

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.

index.js
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 the l character in the string and replace it with an underscore.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee