Replace the First Character in a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Replace the First Character in a String #

To replace the first character in a string:

  1. Assign the character at index 0 to a variable.
  2. Use the String.replace() method to replace the character in the string.
  3. The replace method will return a new string with the first character replaced.
index.js
const str = 'best'; const char = str[0]; console.log(char); // 👉️ b const replaced = str.replace(char, 't'); console.log(replaced); // 👉️ test

The arguments we passed to the String.replace method are:

  1. A substring to be replaced in the string
  2. The replacement string

You will most commonly see the replace method being passed a regular expression as the first parameter. However, we can also use a string for a literal match.

By default, the replace method replaces only the first match in the string, so it does exactly what we need.

The replace method doesn't mutate the original string, it returns a new string with one or more matches replaced. Strings are immutable in JavaScript.

Alternatively, you can use the substring method.

To replace the first character in a string:

  1. Use the substring() method to get a substring starting at the second character.
  2. Prepend the replacement character using the addition + operator.
index.js
const str = 'best'; const replaced = 't' + str.substring(1); console.log(replaced); // 👉️ test

We replaced the character b with the character t.

The only argument we passed to the String.substring method is the start index - the index of the first character to be included in the returned string.

We omit the first character of the original string and prepend a replacement string to the rest.

JavaScript indexes are zero-based. The first character in a string has an index of 0 and the last character has an index of str.length - 1.

Note that the substring method doesn't change the original string, it returns a new string containing the specified part of the original string.

This approach also works if you need to replace the first character with multiple characters.

index.js
const str = 'best'; const replaced = 'the t' + str.substring(1); console.log(replaced); // 👉️ the test

The example replaces the character at index 0 with multiple characters.

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.