How to use the slice() method In Javascript
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.
- The string is first divided into two parts by splitting it where the new string has to be inserted.
- The first part of the string is extracted using the starting position as 0 and the ending position as the index where the new string has to be inserted. The second part of the string is extracted using the starting position as the index where the new string has to be inserted.
- The ending position is optional here and it will be assumed till the end of the string. The new string is added in between these two parts by simple string concatenation.
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
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