Home >Web Front-end >JS Tutorial >How Can I Replace a Character at a Specific Index in a JavaScript String?
Replacing Characters in JavaScript Strings by Index
When working with strings in JavaScript, it can be necessary to replace a character at a specific index. Unfortunately, JavaScript strings are immutable, meaning you cannot directly modify them.
To address this, you can utilize the following approach:
Creating a Custom replaceAt() Function
Define the replaceAt() function to facilitate character replacement at a specified index:
String.prototype.replaceAt = function(index, replacement) { return this.substring(0, index) + replacement + this.substring(index + replacement.length); };
Usage
Once the replaceAt() function is defined, you can utilize it to replace characters in a string:
var str = "hello world"; alert(str.replaceAt(2, "!!")); // He!!o World
In this example, the character at index 2 (the third character) is replaced with "!!". The alert() function displays the updated string.
The above is the detailed content of How Can I Replace a Character at a Specific Index in a JavaScript String?. For more information, please follow other related articles on the PHP Chinese website!