JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to insert string at a specific index of another string in JavaScript?

To insert a string at a specific index, you have to extract two substrings:

  1. A part of the string before the index position, i.e., str.slice(0, index).
  2. Substring from the index position to the end of the string, i.e., str.slice(index).

Once you have the substrings, simply use template literal or addition operator (+) to insert the string between the two substrings.

str.slice(0, index) + "string to be inserted" + str.slice(index)
`${str.slice(0, index)}string to be inserted${str.slice(index)}`

Let's check out the code to insert string at a specific index position:

let str = "React Vue";
let index = 5;

let result = str.slice(0, index) + " Angular" + str.slice(index);
console.log(result); //"React Angular Vue"

result = `${str.slice(0, index)} Angular${str.slice(index)}`;
console.log(result); //"React Angular Vue"

Note: String in JavaScript follows zero-based indexing, which means the first character is at 0th position, and the last character is at "string.length - 1".

The slice() method takes two parameters:

  • startIndex: the index position of the first character that will be included in the substring.
  • endIndex: It is not included in the string. In fact, endIndex - 1 index position is included.

You can also use the substring() method to achieve the same result.

let str = "React Vue";
let index = 5;

let result = str.substring(0, index) + " Angular" + str.substring(index);
console.log(result); //"React Angular Vue"

result = `${str.substring(0, index)} Angular${str.substring(index)}`;
console.log(result); //"React Angular Vue"

Recommended Posts