JavaScript Insert a string at position X of another string
Last Updated :
24 Jun, 2024
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
// 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(''))
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));
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(''))
Method 4: Using JavaScript String concat() Method
The concat() method concatenates the string arguments to the calling string and returns a new string.
Syntax:
string.concat(string2, string3, ..., stringN)
Example: This example demonstrates how to insert one string into another using the concat() method by breaking the main string into two parts and then concatenating them with the substring in between.
JavaScript
// Input string
let str = 'GeeksGeeks';
// Input Substring
let subStr = 'for';
// Index to add substring
let pos = 5;
// Using concat() to insert the substring
let result = str.slice(0, pos).concat(subStr, str.slice(pos));
console.log(result);
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.
Syntax:
string.substring(startIndex, endIndex)
- startIndex: The index at which to begin extraction. If negative, it is treated as str.length + startIndex. (For example, if startIndex is -3, it is treated as str.length – 3.)
- endIndex: The index at which to end extraction. If omitted, the slice goes to the end of the string. If negative, it is treated as str.length + endIndex. (For example, if endIndex is -3, it is treated as str.length – 3).
Example:
JavaScript
// Input string
let str = 'GeeksGeeks';
// Input Substring
let subStr = 'for';
// Index to add substring
let pos = 5;
// Using substring() to insert the substring
let result = str.substring(0, pos) + subStr + str.substring(pos);
console.log(result);
Method 6: Using Template Literals
Template literals in JavaScript provide a powerful way to insert one string into another at a specified position. By using backticks and the ${} syntax, you can easily create a new string with the desired substring inserted at the specified index.
Example:
JavaScript
function insertStringAtPosition(originalString, stringToInsert, position) {
// Using template literals to construct the new string
const newString = `${originalString.slice(0, position)}${stringToInsert}${originalString.slice(position)}`;
return newString;
}
// Example usage:
const originalString = "Hello, World!";
const stringToInsert = " Amazing";
const position = 7;
const result = insertStringAtPosition(originalString, stringToInsert, position);
console.log(result); // Output: "Hello, Amazing World!"
OutputHello, AmazingWorld!
Similar Reads
How to Get Character of Specific Position using JavaScript ?
Get the Character of a Specific Position Using JavaScript We have different approaches, In this article we are going to learn how to Get the Character of a Specific Position using JavaScript Below are the methods to get the character at a specific position using JavaScript: Table of Content Method 1
4 min read
Remove a Character From String in JavaScript
In JavaScript, a string is a group of characters. Strings are commonly used to store and manipulate text data in JavaScript programs, and removing certain characters is often needed for tasks like: Removing unwanted symbols or spaces.Keeping only the necessary characters.Formatting the text.Methods
3 min read
Reverse a String in JavaScript
We have given an input string and the task is to reverse the input string in JavaScript. Using split(), reverse() and join() MethodsThe split() method divides the string into an array of characters, reverse() reverses the array, and join() combines the reversed characters into a new string, effectiv
1 min read
JavaScript - Convert String to Title Case
Converting a string to title case means capitalizing the first letter of each word while keeping the remaining letters in lowercase. Here are different ways to convert string to title case in JavaScript. 1. Using for LoopJavaScript for loop is used to iterate over the arguments of the function, and
4 min read
JavaScript - Sort an Array of Strings
Here are the various methods to sort an array of strings in JavaScript 1. Using Array.sort() MethodThe sort() method is the most widely used method in JavaScript to sort arrays. By default, it sorts the strings in lexicographical (dictionary) order based on Unicode values. [GFGTABS] JavaScript let a
3 min read
How to Convert String to Camel Case in JavaScript?
We will be given a string and we have to convert it into the camel case. In this case, the first character of the string is converted into lowercase, and other characters after space will be converted into uppercase characters. These camel case strings are used in creating a variable that has meanin
4 min read
Extract a Number from a String using JavaScript
We will extract the numbers if they exist in a given string. We will have a string and we need to print the numbers that are present in the given string in the console. Below are the methods to extract a number from string using JavaScript: Table of Content Using JavaScript match method with regExUs
4 min read
JavaScript - Delete First Character of a String
To delete the first character of a string in JavaScript, you can use several methods. Here are some of the most common ones Using slice()The slice() method is frequently used to remove the first character by returning a new string from index 1 to the end. [GFGTABS] JavaScript let s1 = "Geeksfor
1 min read
JavaScript - How to Get Character Array from String?
Here are the various methods to get character array from a string in JavaScript. 1. Using String split() MethodThe split() Method is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument. [GFGTABS] JavaScript let
2 min read
JavaScript - How To Get The Last Caracter of a String?
Here are the various approaches to get the last character of a String using JavaScript. 1. Using charAt() Method (Most Common)The charAt() method retrieves the character at a specified index in a string. To get the last character, you pass the index str.length - 1. [GFGTABS] JavaScript const s =
3 min read