The replaceAt() method is useful for removing the character at a given place. Unfortunately, the replaceAt() method is not a built-in method in JavaScript. It would need to be defined by the user in order to use it. One possible implementation of a replaceAt() function could take a string and two index arguments, and use the JavaScript splice() method to remove the character at the specified index and insert the new character in its place. We declare this method by specifying it in String.prototype.
Syntax:
string.replaceAt(replace_position, replace_char);
Parameters: This method accepts two parameters.
- replace_position: It is the value that we want to replace in the existing string.
- replace_char: It is the new value that is to be put in the place of replace_position.
Return Value: This method returns a new string where the desired values have been replaced.
Example:
Input: str = hello world replace_position = 2 replace_char = k Output: hello world Input: str = Geeks for neveropen replace_position = 4 replace_char = d Output: Geeks for neveropen
Here is an example of how this function could be defined:
Example 1:
Javascript
// JavaScript program to demonstrate replaceAt() method String.prototype.replaceAt = function (index, replacement) { return this .substr(0, index) + replacement + this .substr(index + replacement.length); } let str = "Hello World" ; let replace_position = 1; let replace_char = "a" ; let newStr = str.replaceAt(replace_position,replace_char); console.log(newStr); |
Output:
Hallo World
Example 2:
Javascript
// JavaScript program to demonstrate replaceAt() method String.prototype.replaceAt = function (index, replacement) { return this .substr(0, index) + replacement + this .substr(index + replacement.length); } let str = "Geeks for neveropen" ; let replace_position = 4; let replace_char = "d" ; let newStr = str.replaceAt(replace_position,replace_char); console.log(newStr); |
Output:
Geeks for neveropen
We have a complete list of Javascript Strings methods, to check those please go through Javascript String Complete reference article.