Open In App

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

In this article, we are given a string containing words and the task is to insert a new string at a given index. Inserting string at a particular position means increasing the length of the original string.There are some methods like slice( ), splice( ), and substring( ) to solve this problem which are discussed below: 

Method 1: Using the slice() method

The slice() method is used to return an array between two indices. It takes two parameters, one is the beginning index which specifies and the other is the ending index. 

Syntax:



let newString = originalString.slice(startIndex, endIndex);

Example: This example shows the above-explained approach.




// Input String
let origString = "GeeksGeeks";
 
// String to be added
let stringToAdd = "For";
 
// Position to add string
let indexPosition = 5;
 
// Using slice method to split string
newString = origString.slice(0, indexPosition)
        + stringToAdd + origString.slice(indexPosition);
 
// Display output
console.log(newString);

Output
GeeksForGeeks

Method 2: Using the splice() method

The splice() method is used to insert or replace the contents of an array at a specific index. This can be used to insert the new string at the position of the array.

Syntax:

str.splice(index, 0, element);

Example: This example shows the above-explained approach.




// Input String
let origString = "GeeksGeeks";
 
// String to be added
let stringToAdd = "For";
 
// Position to add string
let indexPosition = 5;
 
// Split the string into individual
// characters
origString = origString.split('');
     
// Insert the string at the index position
origString.splice(indexPosition, 0, stringToAdd);
     
// Join back the individual characters
// to form a new string
newString = origString.join('');
     
// Display output
console.log(newString);

Output
GeeksForGeeks

Method 3: Using JavaScript substring() method

The string.substring() is an inbuilt function in JavaScript that is used to return the part of the given string from the start index to the end index. Indexing start from zero (0). 

Syntax: 

string.substring(Startindex, Endindex)

Example: In this example, we will split the string using substring method and add the given string at the given index.




// Input String
let origString = "GeeksGeeks";
// String to be added
let stringToAdd = "For";
// Position to add string
let indexPosition = 5;
 
// Using substring method to split string
newString = origString.substring(0, indexPosition)
        + stringToAdd + origString.substring(indexPosition);
 
// Display output
console.log(newString);

Output
GeeksForGeeks

Article Tags :