How to use splice() method In Javascript

The JavaScript Array splice() Method is an inbuilt method in JavaScript that is used to modify the contents of an array by removing the existing elements and/or by adding new elements.

Syntax:

Array.splice( index, remove_count, item_list )

Example:

Javascript
// Input string
let str = 'GeeksGeeks'

// Input Substring
let subStr = 'for'

// Index to add substring
let pos = 5

// Convert to array of string
let arr = str.split('')

// Add substring at given position
arr.splice(pos, 0, ...subStr)

// Display result
console.log(arr.join(''))

Output
w3wiki

JavaScript Insert a string at position X of another string

Given two strings, the task is to insert one string in another at a specified position using JavaScript. We’re going to discuss a few methods, these are:

Similar Reads

Methods to Insert String at a Certain Index

Table of Content Method 1: Using JavaScript String slice() and Array join() MethodsMethod 2: JavaScript String substr() Method Method 3: Using JavaScript splice() methodMethod 4: Using JavaScript String concat() MethodMethod 5: Using String.substring() Method...

Method 1: Using JavaScript String slice() and Array join() Methods

This method gets parts of a string and returns the extracted parts in a new string. Start and end parameters are used to specify the part of the string to extract. The first character starts from position 0, the second has position 1, and so on....

Method 2: JavaScript String substr() Method

This method gets parts of a string, starting at the character at the defined position, and returns the specified number of characters....

Method 3: Using JavaScript splice() method

The JavaScript Array splice() Method is an inbuilt method in JavaScript that is used to modify the contents of an array by removing the existing elements and/or by adding new elements....

Method 4: Using JavaScript String concat() Method

The concat() method concatenates the string arguments to the calling string and returns a new string....

Method 5: Using String.substring() Method

The substring() method extracts the characters from a string between two specified indices and returns a new string. We can utilize this method to split the original string into two parts at the specified index, then concatenate the substring in between....