In JavaScript, inserting a string at a specific index creates a new string by placing the new content between parts of the original string.
- Strings remain unchanged because they are immutable.
- Different methods can be used based on readability and requirements.
- The result combines the original content with the inserted string at the desired position.
Approach 1: Using the slice() Method
The slice() method divides the original string into two parts at the specified index. The new string is placed between these two parts to create the updated string.
let str = "GeeksGeeks";
let str2 = "For";
let idx = 5;
let res = str.slice(0, idx) + str2 + str.slice(idx);
console.log(res);
Approach 2: Using the substring() Method
The substring() method can also divide a string into two parts. The new string is inserted between the extracted portions.
let str = "GeeksGeeks";
let str2 = "For";
let idx = 5;
let res = str.substring(0, idx) + str2 + str.substring(idx);
console.log(res);
Approach 3: Using a Regular Expression
A regular expression can insert a string after a matched group of characters using the replace() method.
let str = "hello";
let res = str.replace(/(.{3})/, "$1***");
console.log(res);
Approach 4: Using Template Literals
Template literals provide a clean and readable way to combine different parts of a string with the new content.
const str = "Hello, World!";
const str1 = "Amazing ";
const idx = 7;
const s1 = str.slice(0, idx);
const s2 = str.slice(idx);
const res = `${s1}${str1}${s2}`;
console.log(res);
Approach 5: Using the Array Spread Operator
This approach uses the Spread Operator to convert the string into an array of characters. The splice() method inserts the new string at the specified index, and join() converts the array back into a string.
let str = "HelloWorld";
let str1 = "Beautiful";
let idx = 5;
let arr = [...str];
arr.splice(idx, 0, ...str1);
let res = arr.join("");
console.log(res);
Approach 6: Using Loops
Loops provide manual control over the insertion process by constructing a new string character by character.
function insertAt(str, str1, idx) {
if (idx < 0 || idx > str.length) {
return str;
}
let res = "";
for (let i = 0; i < str.length; i++) {
if (i === idx) {
res += str1;
}
res += str[i];
}
if (idx === str.length) {
res += str1;
}
return res;
}
let str = "Hello World!";
let str1 = "JavaScript ";
let idx = 6;
console.log(insertAt(str, str1, idx));