Given a String, the task is to replace a character at a specific index in a string in JavaScript. It is basically used for text manipulation.
There are several approaches to replace character at a specific index in JavaScript. We will explain each approaches in detail with description and examples.
Approach 1: Using String Manipulation
One approach is to split the string into an array of characters, replace the character at the desired index, and then join the array back into a string.
let str = "hello world"; const index = 4; const newChar = 'X'; str = str.substring(0, index) + newChar + str.substring(index + 1); console.log(str); // Output: "hellX world"
- Explanation: This approach uses the
substring()
method to split the string into two parts at the specified index. Then, it replaces the character at the index with the new character.
Approach 2: Using String Concatenation
You can also achieve this by concatenating substrings before and after the character to be replaced with the new character.
let str = "hello world"; const index = 4; const newChar = 'X'; str = str.slice(0, index) + newChar + str.slice(index + 1); console.log(str); // Output: "hellX world"
- Explanation: The
slice()
method works similarly tosubstring()
but allows negative indices and works better with arrays.
Approach 3: Using Array Splice
Converting the string to an array, replacing the character using array manipulation methods, and then joining it back into a string is another option.
let str = "hello world"; const index = 4; const newChar = 'X'; const chars = str.split(''); chars.splice(index, 1, newChar); str = chars.join(''); console.log(str); // Output: "hellX world"
- Explanation: This approach splits the string into an array of characters, replaces the character at the specified index using
splice()
, and then joins the array back into a string.
Approach 4: Using String Replace
The replace()
method with a regular expression can also be used to replace characters at specific indices.
let str = "hello world"; const index = 4; const newChar = 'X'; str = str.replace(new RegExp(`^(.{${index}}).`), `$1${newChar}`); console.log(str); // Output: "hellX world"
- Explanation: This approach uses a regular expression to match the substring up to the specified index, and then replaces the next character with the new character.