Skip to content

How to Replace the Last Character of a String in JavaScript

Learn how to replace the last character in a JavaScript string using immutable string operations with slice() or regex replace(), including edge-case handling.

Replacing the final character of a string is a common formatting task. For example, you might need to change a file extension, correct a trailing punctuation mark, or simply update the end of a generated string. Since strings in JavaScript are immutable, you cannot change the last character in place; you must create a new string with the desired modification.

This guide will demonstrate the modern and most recommended method for this task using String.prototype.slice(). We will also cover an effective alternative using String.prototype.replace() with a regular expression.

The Core Problem: Strings are Immutable

A fundamental property of JavaScript strings is that they cannot be changed. You cannot reassign a character at a specific index like you can with an array.

Problem:

// Problem: This does not work.
let myString = 'Hello';
myString[4] = '!';      // Attempting to change 'o' to '!'

console.log(myString);

Output: (The string is unchanged)

Hello

The most direct and readable way to replace the last character is to "slice" off the end of the string and then concatenate your new character.

Logic

  1. Use slice(0, -1) to get a new string containing everything except the last character.
  2. Use the + operator to append your new character to the end of that new string.

Solution:

function replaceLastChar(str, replacement) {
  return str.slice(0, -1) + replacement;
}

// Example Usage:
let originalString = 'tutorialreference.com';
let newString = replaceLastChar(originalString, '_');

console.log(newString);

Output:

tutorialreference.co_

An Alternative Method: replace() with a Regular Expression

You can also use a regular expression to find and replace the last character in the string. This method is equally effective but can be slightly less readable for developers unfamiliar with regex.

Solution:

function replaceLastCharRegex(str, replacement) {
  // The regex /.$/ matches any single character at the end of the string.
  return str.replace(/.$/, replacement);
}

// Example Usage:
let originalString = 'Hello World.';
let newString = replaceLastCharRegex(originalString, '!');

console.log(newString);

Output:

Hello World!

How the Regex Works

  • / ... /: The delimiters for the regular expression.
  • .: A special "metacharacter" that matches any single character (except for line terminators).
  • $: An "anchor" that asserts that the pattern must occur at the end of the string.

So, /.$/ translates to: "Find any single character that is at the very end of the string."

Practical Example: A Reusable replaceLastChar Function

This example creates a robust, reusable function that includes a check to handle empty strings gracefully.

/**
 * Replaces the last character of a string with a new character or string.
 * @param {string} str The original string.
 * @param {string} replacement The string to append in place of the last character.
 * @returns {string} The new, modified string.
 */
function replaceLastChar(str, replacement) {
  // Handle empty or single-character strings
  if (str === '') {
    return replacement;
  }
  return str.slice(0, -1) + replacement;
}

// Example Usage:
console.log(replaceLastChar('file.txt', 'csv'));  // Output: file.tcsv
console.log(replaceLastChar('done!', '?'));       // Output: done?
console.log(replaceLastChar('', 'start'));        // Output: start

Output:

file.txcsv
done?
start

Conclusion

Because strings are immutable, replacing the last character requires creating a new string.

  • The slice() method is the recommended best practice. It is highly readable, performant, and its intent is very clear: str.slice(0, -1) + replacement.
  • The replace() method with the /.$/ regex is an excellent and equally valid alternative, especially if you are already comfortable with regular expressions.
Navigation