Replace the First Occurrence of Character in String in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 the example, we replaced the l character with an underscore _.

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

If you need help reading or writing a regular expression, check out this regex cheatsheet from MDN.

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 replaced it with an underscore.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.