This post will discuss how to replace a character at the specified index in JavaScript.

The strings are immutable in JavaScript, which means we can’t change their content once created. So, the idea is to create a new string with the replaced character. You can do this in two ways:

1. Using String.prototype.substring() function

The idea is to split the string into two substrings before and after the specified position, and then concat them together with the specified character in the middle. Following is a simple example demonstrating this:

Download  Run Code

 
Note that the substr() function also works similarly, but we recommend against using it.

2. Using Character Array

Another approach is to convert the string to a character array, replace the value at the specified index with the given character, and join it back together into a string. This would translate to a simple code below:

Download  Run Code

That’s all about replacing a character at the specified index in JavaScript.