How To Replace The First Occurrence Of Character In JavaScript String

Replace the First Occurrence of Character in String in JS

JavaScript offers some simple ways to replace the first or all characters in String. Today we will show you how to replace the first occurrence of character in JavaScript string. This article will show you many methods, like using the replace() method and using the replace() method with the ‘i’ modifier. Start reading the detailed article.

Replace the first occurrence of character in JavaScript string

Using the replace() method

The simple and easy way is using the replace() method to do it. This method has been introduced by us here. Please read it to get more information.

Code example:

In this example, we will replace the “l” character in myString:

  • First of all, we just call the replace method in the myString to replace the ‘l’ character with a space character.
  • And then, print out the result into the console by calling the console.log() method. See the example below to get more information
const myString = 'Wellcome';
console.log("My string is: ", myString);

// Using the replace() method 
const newString = myString.replace(/l/, '');
console.log("After replacing the first occurrence of character: ", newString);

Output

My String is: Wellcome
After replacing the first occurrence of character: Welcome

Using the replace() method with the ‘i’ modifier

The next way is calling the replace() method with the ‘i’ modifier. This way is the same as the first way, but we are using the ‘i’ modifier to only replace the first occurrence of the character in String. JavaScript offers you the regular expression to do it. Let’s see the code example below.

Example:

In this example, we will be using the regular expression with the ‘i’ modifier. The “i” modifier only replaces the first occurrence match in the String.

const myString = 'Wellcome';
console.log("My string is: ", myString);

// Using the replace() method with i modifier, replace the first l with '' character
const newString = myString.replace(/l/i, '');
console.log("After replacing the first occurrence of character: ", newString);

Output

My String is: Wellcome
After replacing the first occurrence of character: Welcome

Browser Support

/regexp/i is an ECMAScript1 (ES1) feature.

This feature is supported in all browsers, and you can use it for all browsers. Very common function in JavaScript.

Summary

In this article, we have already explained many ways to replace the first occurrence of character in JavaScript string. However, using the replace() method is the simple and easy way. What about your opinion? Leave your comment here to let us know. Thanks for your reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *