Open In App

JavaScript Insert a string at position X of another string

Improve
Improve
Like Article
Like
Save
Share
Report

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

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(''))


Output

GeeksforGeeks

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));


Output

GeeksforGeeks

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(''))


Output

GeeksforGeeks



Last Updated : 20 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads