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
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
let str = 'GeeksGeeks'
let subStr = 'for'
let pos = 5
console.log([str.slice(0, pos), subStr, str.slice(pos)].join( '' ))
|
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
let str = 'GeeksGeeks' ;
let subStr = 'for' ;
let pos = 5;
console.log(str.substr(0, pos) + subStr + str.substr(pos));
|
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
let str = 'GeeksGeeks'
let subStr = 'for'
let pos = 5
let arr = str.split( '' )
arr.splice(pos, 0, ...subStr)
console.log(arr.join( '' ))
|