Replace a character at specific index in JavaScript
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
String.prototype.replaceAt = function(index, replacement) { if (index >= this.length) { return this.valueOf(); } return this.substring(0, index) + replacement + this.substring(index + 1); } var str = "Hello World"; str = str.replaceAt(5, '_'); console.log(str); /* Output: Hello_World */ |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
String.prototype.replaceAt = function(index, replacement) { if (index >= this.length) { return this.valueOf(); } var chars = this.split(''); chars[index] = replacement; return chars.join(''); } var str = "Hello World"; str = str.replaceAt(5, '_'); console.log(str); /* Output: Hello_World */ |
That’s all about replacing a character at the specified index in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)