Insert String at specific Index of another String in JS

avatar

Borislav Hadzhiev

Wed Nov 17 20212 min read

Insert String at specific Index of another String #

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.

index.js
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:

  1. the start index - the index of the first character to be included in the new string
  2. the end index - go up to, but not including this index

To get the portion of the string before the specified index, we go from index 0 up to, but not including the provided index.

index.js
const str = 'he world'; // ๐Ÿ‘‡๏ธ "he" console.log(str.slice(0, 2));
Indexes are zero-based in JavaScript. The index of the first character in a string is 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.

index.js
const str = 'he world'; // ๐Ÿ‘‡๏ธ " world" console.log(str.slice(2));

You could achieve the same result using the String.substring method.

index.js
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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee