Borislav Hadzhiev
Mon Oct 11 2021·3 min read
Photo by Stefan Widua
To replace a character at a specific index in a string:
substring()
method twice to get the string in two pieces,
excluding the character to be replaced.+
operator to add the replacement character between the two
strings.const str = 'bob'; const index = 2; const replacement = 'x'; const replaced = str.substring(0, index) + replacement + str.substring(index + 1); console.log(replaced); // 👉️ box
The parameters we pass to the String.substring method are:
substring
method does not change the original string, instead it returns a new string containing a part of the original string.In the example, we replace the character at index 2
, which is a b
with an
x
.
An easy way to think about this is:
The first call to the substring
method returns a string starting at index
0
of the original string and going up to, but not including the index of
the character we want to replace
We then add the replacement character to the string
The last step is to add the rest of the string. However, we don't want to include the character that we already replaced, so we increment the start index by 1.
This approach also works if you need to replace a single character with multiple characters, starting at a specific index.
const str = 'This is a long string'; const index = 8; const replacement = 'a very'; const replaced = str.substring(0, index) + replacement + str.substring(index + 1); // 👇️ This is a very long string console.log(replaced);
We use the exact same approach as from the first code snippet, however this time
we replace a single character - a
with multiple characters - a very
.
To replace multiple characters at a specific index, use the length of the
replacement string to determine the start index of the second call to
substring()
.
const str = 'the best'; const index = 4; const replacement = 'test'; const replaced = str.substring(0, index) + replacement + str.substring(index + replacement.length); console.log(replaced); // 👉️ the test
In this example we replace the word best
with the word test
.
Here's what we did to achieve this:
substring
method we get the part of the original
string from index 0
up to but not including the index of the characters to
be replaced.substring
method should start.