Sometimes, we need to replace a character at a particular index in our JavaScript strings.
In this article, we’ll look at how to replace a character at a particular index with JavaScript.
Use the String.prototype.substr Method
We can extract substrings from a string with the substr
method.
This will help us with the replacement since we can extract the substrings from index 0 to the index of the character we want to replace.
And we can extract the string from the index to the end of the string.
Then we can add the replacement between the 2 substrings.
For instance, we can write:
const replaceAt = (str, index, replacement) => {
return str.substr(0, index) + replacement + str.substr(index + 1);
}
const str = 'a b c'
const newStr = replaceAt(str, 2, 'foo')
console.log(newStr)
We create the replaceAt
function which takes the str
string that we want to the replacement with.
The index
of the character that we want to replace.
And replacement
is the replacement string.
Then we return the first substring concatenated with the replacement
concatenated with the 2nd substring.
So when we pass in the arguments to it, we get newStr
, which is:
'a foo c'
The substr
and substring
method are the same so we can write:
const replaceAt = (str, index, replacement) => {
return str.substring(0, index) + replacement + str.substring(index + 1);
}
const str = 'a b c'
const newStr = replaceAt(str, 2, 'foo')
console.log(newStr)
We can use this to replace any character with another substring of any length.
String.prototype.split and String.prototype.join
We can also use the split
and join
methods to split and join a string together.
For instance, we can write:
let str = 'a b c'
str = str.split('');
str[2] = 'd';
str = str.join('');
console.log(str)
We call split
with an empty string to split the string into an array of characters.
Then we assign the character of a string with the given index with a new character.
And then we join the string back together with the join
method and an empty string as an argument.
Therefore, str
should be 'a d c’
.
This is handy for replacing one character with another.
Conclusion
To replace a character with another substring, we can split the string into substrings.
Then we can join them back together with a replacement.
We can also split a string into an array of characters, assign the character at the position to another character.
Then we can join the string back together.