How 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 split() with the separator as a blank character ("").

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

Javascript replaced character
String.prototype.replaceAt = function (index, char) { let a = this.split(""); a[index] = char; return a.join(""); } let str = "Welcome W3Docs"; str = str.replaceAt(7, "_"); console.log(str);

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 length parameter 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 skipped to retrieve the whole string after it.

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
String.prototype.replaceAt = function (index, replacement) { if (index >= this.length) { return this.valueOf(); } return this.substring(0, index) + replacement + this.substring(index + 1); } let str = "Welcome W3docs"; str = str.replaceAt(7, '-'); console.log(str);

The split() and join() Methods

The split() method cuts the string into substrings, puts them into an array, and returns it. The division is achieved by searching for a pattern provided as the first parameter in the method's call. The join() method is invoked to reverse the split.The substring() Method

The substring() method returns the string part between the start and end indexes, or to the end of the string. It extracts a substring from a specified starting index to another index used to extract the parts of the string excluding the character which should be replaced.