How to use the splice() method In Javascript
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.
- It takes 3 parameters, the index where the string is to be inserted, the number of deletions to be performed if any, and the string to be inserted.
- The required index and the string are passed as parameters to this method with the deletions parameter set to 0. It inserts the string into the array.
- The array is joined back using the join() method. This makes it one whole string again with the new string joined in between.
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
w3wiki
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:
Table of Content
- Method 1: Using the slice() method
- Method 2: Using the splice() method
- Method 3: Using JavaScript substring() method
- Method 4: Using String Concatenation