How to Replace the First Occurrence of a Character in a String in JavaScript

Updated onbyAlan Morel
How to Replace the First Occurrence of a Character in a String in JavaScript

Working with strings in JavaScript is a common task.

One of the most useful things to know how to do is to replace the first occurrence of a character in a string.

For example, if you're working with a string representing a dollar amount, you might want to remove the dollar sign.

In this post, we'll learn how to replace the first occurrence of a character in a string using JavaScript.

Replace the first occurrence of a character in a string in JavaScript

The easiest way to replace the first occurrence of a character in a string is to use the replace() method.

This method takes two arguments:

  1. The character to replace
  2. The character to replace it with

By default, it will only replace the first occurrence of the character.

Let's look at an example:

JAVASCRIPT
const string = "$100"; const newString = string.replace("$", ""); console.log(newString);
BASH
100

Notice how even if we had another dollar sign, it would still only replace the first occurrence.

JAVASCRIPT
const string = "$100$"; const newString = string.replace("$", ""); console.log(newString);
BASH
100$

Another way we can do this is by using regular expressions.

Regular expressions are a powerful tool for working with strings.

Here's how we can use them to replace the first occurrence of a character in a string:

JAVASCRIPT
const string = "$100"; const newString = string.replace(/\$/, ""); console.log(newString);
BASH
100

In all of our earlier examples, we are replacing the first occurrence of a character with an empty string, however, we can replace it with any character we want.

For example, we could replace the first occurrence of a dollar sign with a pound sign:

JAVASCRIPT
const string = "$100"; const newString = string.replace("$", "£"); console.log(newString);
BASH
£100

Conclusion

In this post, we learned how to replace the first occurrence of a character in a string using JavaScript.

Simply use the replace() method and pass in the character you want to replace and the character you want to replace it with.

Alternatively, you can use regular expressions to accomplish the same thing.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.