Skip to main content

How to Replace a Character at a Specific Index in a String in JavaScript

Replacing a character at a specific position in a string is a common requirement in text manipulation. Since strings in JavaScript are immutable, you cannot change a character in place. Instead, you must create a new string with the desired character replaced.

This guide will demonstrate the standard and most recommended method for this task using String.prototype.slice(). We will also cover an alternative method that uses array conversion and splice() to explain why it's less efficient.

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.

Example of problem:

// Problem: This does not work.
let myString = 'Hello';
myString[1] = 'a'; // Attempting to change 'e' to 'a'

console.log(myString); // Output: "Hello" (The string is unchanged)
note

To "change" a string, you must always create a new string with the desired modifications.

The most direct and readable way to replace a character is to "slice" the original string into two parts at the target index, and then concatenate them back together with the new character in the middle.

Solution: this function replaces the character at index with replacement.

function replaceAt(originalString, index, replacement) {
// 1. Get the part of the string before the index.
const start = originalString.slice(0, index);

// 2. Get the part of the string after the character to be replaced.
const end = originalString.slice(index + 1);

// 3. Concatenate the parts with the replacement character.
return start + replacement + end;
}

// Example Usage:
const str = 'tommy';
const result = replaceAt(str, 2, '_'); // Replace character at index 2 ('m')

console.log(result); // Output: "to_my"
note

This method is clear, non-mutating, and is the idiomatic way to solve this problem. It can also be used to replace a single character with multiple characters.

console.log(replaceAt('tommy', 2, '!!!')); // Output: "to!!!my"

How the slice() Method Works

string.slice(startIndex, endIndex)

extracts a section of a string and returns it as a new string.

Let's break down the function replaceAt('tommy', 2, '_'):

  • originalString.slice(0, 2): Slices from index 0 up to (but not including) index 2. This returns "to".
  • originalString.slice(2 + 1): Slices from index 3 all the way to the end of the string. This returns "my".
  • The final concatenation becomes "to" + "_" + "my", resulting in "to_my".

An Alternative (Less Efficient) Method: split(), splice(), and join()

Another way to approach this is to convert the string to an array of characters, modify the array, and then join it back into a string.

function replaceAtWithSplice(str, index, replacement) {
// 1. Convert the string to an array of characters.
const arr = str.split('');

// 2. Use splice to replace the character at the index.
// (At index, remove 1 item, and insert `replacement`)
arr.splice(index, 1, replacement);

// 3. Join the array back into a string.
return arr.join('');
}

// Example Usage:
console.log(replaceAtWithSplice('tommy', 2, '_')); // Output: "to_my"

While this works, it is less efficient than the slice() method because it involves the overhead of creating an intermediate array and then re-joining it. For performance-sensitive code, the slice() method is superior.

Practical Example: A Reusable replaceAt Function

This example creates a robust, reusable function that includes boundary checks to prevent errors.

/**
* Replaces the character at a specific index in a string.
* @param {string} str The original string.
* @param {number} index The zero-based index of the character to replace.
* @param {string} replacement The character to insert.
* @returns {string} The new string with the character replaced.
*/
function replaceAt(str, index, replacement) {
if (index < 0 || index >= str.length) {
// Return the original string if the index is out of bounds
return str;
}
return str.slice(0, index) + replacement + str.slice(index + 1);
}

// Example Usage:
const word = 'JavaScript';
const correctedWord = replaceAt(word, 4, 's'); // Correct the casing of 's'

console.log(correctedWord); // Output: "Javascript"

Conclusion

Because strings are immutable in JavaScript, replacing a character requires creating a new string.

  • The slice() method is the recommended best practice. It is highly readable, efficient, and directly manipulates the string. The pattern is str.slice(0, index) + replacement + str.slice(index + 1).
  • Avoid the split/splice/join method, as it is less performant due to the unnecessary creation of an intermediate array.