W3docs

How to Replace a Character at a Particular Index in JavaScript

In this tutorial, you will read and learn detailed information about methods that are used to replace a character at a particular index in JavaScript.

JavaScript strings are immutable, which means they cannot be altered after they are created. For this reason, you should create a new string with replaced character. Here are two methods of doing it.

split() and join()

The first method is split and join which converts the string into an array and replaces the character at the specified index. The string is converted into an array by using <kbd class="highlighted">split()</kbd> with the separator as a blank character <kbd class="highlighted">""</kbd>.

The replaced character can then be assigned to the corresponding index of the array. Then you can use the <kbd class="highlighted">join()</kbd> method with the separator as a blank character <kbd class="highlighted">""</kbd> to glue the array into a string which will create a new string with the character replaced at the index.

JavaScript replaced character

javascript— editable

substring()

You can also handle the task with the help of the substring() method. Firstly, you should extract the string by using the starting index parameter as '0' and the end index as "index" where the character has to be replaced. Then the string should be extracted by using the starting index parameter as 'index + 1' denoting the string part after the index of the character. The second parameter is omitted to retrieve the rest of the string.

The new string created combining the two parts of the string with the character to be replaced added in between. As a result, a new string is created with the character replaced at the index:

JavaScript replaced character and create new string

javascript— editable