Borislav Hadzhiev
Wed Nov 17 2021·2 min read
Photo by Vadim Sadovski
Use the slice()
method to insert a string at a specific index of another
string, e.g. str.slice(0, index) + 'example' + str.slice(index)
. The slice
method allows us to get the substrings before and after the specific index and
insert another string between them.
const str = 'he world'; const index = 2; const result = str.slice(0, index) + 'llo' + str.slice(index); // 👇️ "hello world" console.log(result);
We passed the following 2 parameters to the String.slice method:
To get the portion of the string before the specified index, we go from index
0
up to, but not including the provided index.
const str = 'he world'; // 👇️ "he" console.log(str.slice(0, 2));
0
, and the last - string.length - 1
.We used the addition (+) operator to concatenate the strings together.
We only passed a single parameter in our second call to the slice()
method -
the start index.
If only a single parameter is provided, the slice
method starts including
characters from the supplied index and goes to the end of the string.
const str = 'he world'; // 👇️ " world" console.log(str.slice(2));
You could achieve the same result using the String.substring method.
const str = 'he world'; const index = 2; const result = str.substring(0, index) + 'llo' + str.substring(index); // 👇️ "hello world" console.log(result);
We passed the same 2
parameters to the substring
method - the start and end
indexes.
For our purposes, the slice
and substring
methods do the same thing, however
there are some
differences between the two.
For example if you pass an end index, which is greater than the start
index to the substring
method, it swaps the parameters, whereas the slice
method returns an empty string.
For this and many other strange decisions in the implementation of the
substring
method, there is no good reason to use it over slice
.