Replace the Last Character in a String in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 11 20212 min read

banner

Photo by Kym MacKinnon

Replace the last character in a String #

To replace the last character in a string:

  1. Call the slice() method, passing it a start index of 0 and an end index of -1 to get a string, containing the characters up to the last one.
  2. Use the + operator to append the replacement character to the string.
index.js
const str = 'Hello World.'; const replaced = str.slice(0, -1) + '!'; console.log(replaced); // ๐Ÿ‘‰๏ธ Hello World!
Indexes are zero-based in JavaScript. The first character in a string has an index of 0 and the last an index of str.length - 1.

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

  1. start index - the index of the first character to be included in the returned string.
  2. end index - go up to, but not including this index. A negative index indicates an offset from the end of the string.
Passing a negative index parameter of -1 and str.length - 1 is the same. We instruct the slice method to go up to, but not including the last character in the string.

By getting a part of the string up to, but not including the last character, we are able to replace it with one or more characters.

This approach also works if we need to replace the last character with multiple characters.

index.js
const str = 'Hello World.'; const replaced = str.slice(0, -1) + '!!!'; console.log(replaced); // ๐Ÿ‘‰๏ธ Hello World!!!

Note that the slice method does not change the contents of the original string, it returns a new string containing a part of the original string.

An alternative, but also very common approach is to use the String.replace method.

To replace the last character in a string:

  1. Call the replace() method, passing it a regular expression that matches the last character in the string and the replacement character as parameters.
  2. The replace method will return a new string with the last character replaced.
index.js
const str = 'Hello World.'; const replaced = str.replace(/.$/, '!'); console.log(replaced); // ๐Ÿ‘‰๏ธ Hello World!

The parameters we passed to the replace method are:

  1. a regular expression to match in the string
  2. a string replacement for the first match of the regular expression

If you ever need help reading a regular expression, check out this regular expression cheatsheet by MDN.

The . character in our regular expression matches any single character.

The $ character matches the end of a string.

This satisfies our requirement to match and replace the last character in the string.

The replace method does not mutate the original string, it returns a new string. Strings are immutable in JavaScript.

I prefer the first approach over using the replace method, because many developers are not familiar with regular expressions.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee