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:
Methods to Insert String at a Certain Index
- using JavaScript String slice() and Array join() Methods
- using JavaScript String substr() Method
- using JavaScript splice() 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.
Syntax:
string.slice(start, end)
JavaScript Array join() Method: This method adds the elements of an array into a string and returns the string. The elements will be separated by a passed separator. The default separator is a comma (, ).
Syntax:
array.join(separator)
Example: This example inserts one string into another by using slice() and join() method.
Javascript
// Input string let str = 'GeeksGeeks' // Input Substring let subStr = 'for' // Index to add substring let pos = 5 console.log([str.slice(0, pos), subStr, str.slice(pos)].join( '' )) |
neveropen
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.
Syntax:
string.substr(start, length)
Example: This example inserts one string to another by using substr() method.
Javascript
// Input string let str = 'GeeksGeeks' ; // Input Substring let subStr = 'for' ; // Given index let pos = 5; // Insert and display output console.log(str.substr(0, pos) + subStr + str.substr(pos)); |
neveropen
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.
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( '' )) |
neveropen