Replace the First Character in a String in JavaScript


Borislav Hadzhiev

Mon Oct 11 20213 min read


Photo by Marko Horvat

Replace the First Character in a String #

To replace the first character in a string:

  1. Call the substring() method, passing it 1 as a start index.
  2. Prepend the replacement character using the plus + operator, e.g. a + str.substring(1).
  3. The substring method will return the part of the string from index 1 to the end.
const str = 'best'; const replaced = 't' + str.substring(1); console.log(replaced); // 👉️ test

In the example we replace the character b with the character t.

The only parameter we pass to the String.substring method is:

  • start index - the index of the first character to be included in the returned string

For our use case we want to exclude the first character in the string and prepend whatever we need.

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

Note that the substring method does not 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.

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

In the code snippet, we replace the character at index 0, which is a b with the characters the t.

An alternative approach is to use the replace method.

To replace the first character in a string:

  1. Assign the character at index 0 of the string to a variable.
  2. Call the replace() method passing it the variable as the first parameter and the replacement character as the second, e.g. str.replace(char, 'a')
  3. The replace method will return a new string with the first character replaced.
const str = 'best'; const char = str[0]; console.log(char); // 👉️ b const replaced = str.replace(char, 't'); console.log(replaced); // 👉️ test

The parameters we pass to the String.replace method are:

  1. a string literal to be replaced
  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 does not mutate the original string, it returns a new string with one or more matches replaced. Strings are immutable in JavaScript.

I prefer the first approach, because it is a bit easier to read and more direct.

Most developers have only used the replace method with a regular expression and not a string literal, so they might be surprised when they see it used like that.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.