Open In App

JavaScript replaceAt() Method

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.

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 geeks
replace_position = 4
replace_char = d

Output:
Geeks for geeks

Here is an example of how this function could be defined:

Example 1:




// 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 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 geeks";
let replace_position = 4;
let replace_char = "d";
let newStr = str.replaceAt(replace_position,replace_char);
console.log(newStr);

Output:

Geeks for geeks

We have a complete list of Javascript Strings methods, to check those please go through Javascript String Complete reference article.


Article Tags :