How to Insert a String at a Specific Index in JavaScript
A common string manipulation task is to insert a new piece of text into the middle of an existing string at a specific position. For example, you might need to insert a middle name into a full name, add a timestamp into a log message, or inject a substring into a template.
This guide will demonstrate the standard and most recommended method for this task using String.prototype.slice(). We will also briefly cover some alternative methods like substring() and explain why slice() is generally preferred.
The Core Method (Recommended): Using String.prototype.slice()
The most direct and readable way to insert a string is to "slice" the original string into two parts at the desired index and then concatenate them back together with the new string in the middle.
For example, you have a string and you want to insert a new substring at a specific index.
// Problem: Insert "llo" at index 2 to form "hello world".
const mainStr = 'he world';
const subStr = 'llo';
const index = 2;
Solution:
function insertAtIndex(originalString, stringToInsert, index) {
// 1. Get the part of the string before the insert point.
const start = originalString.slice(0, index);
// 2. Get the part of the string after the insert point.
const end = originalString.slice(index);
// 3. Concatenate the three parts.
return start + stringToInsert + end;
}
// Example Usage:
const str = 'he world';
const result = insertAtIndex(str, 'llo', 2);
console.log(result); // Output: "hello world"
This method is clear, non-mutating (it creates a new string), and is the idiomatic way to solve this problem.
How the slice() Method Works
string.slice(startIndex, endIndex) extracts a section of a string and returns it as a new string.
startIndex: The zero-based index at which to begin extraction.endIndex(optional): The zero-based index before which to end extraction. If omitted,slice()extracts through the end of the string.
Let's break down the function insertAtIndex('he world', 'llo', 2):
originalString.slice(0, 2): Slices from index 0 up to (but not including) index 2. This returns"he".originalString.slice(2): Slices from index 2 all the way to the end of the string. This returns" world".- The final concatenation becomes
"he" + "llo" + " world", resulting in"hello world".
Alternative Methods (substring and splice)
While slice() is recommended, you may encounter other methods.
Using String.prototype.substring()
The substring() method is very similar to slice(). For this specific use case, it works identically.
function insertWithSubstring(str, sub, index) {
return str.substring(0, index) + sub + str.substring(index);
}
Why slice() is generally preferred: substring() has some quirky behaviors with its arguments (e.g., it swaps them if the start index is greater than the end index), whereas slice() is more predictable. For consistency, most developers prefer slice().
Using Array.prototype.splice()
This method is more complex and less efficient, as it requires converting the string to an array and back again.
function insertWithSplice(str, sub, index) {
const arr = str.split(''); // 1. Convert to array
arr.splice(index, 0, sub); // 2. Insert into array
return arr.join(''); // 3. Convert back to string
}
This is a valid but overly complicated solution. It should be avoided when the simpler string methods are available.
Practical Example: A Reusable insertAt Function
This example creates a robust, reusable function and shows it in action.
/**
* Inserts a substring into a string at a specified index.
* @param {string} originalString The original string.
* @param {string} stringToInsert The string to insert.
* @param {number} index The zero-based index at which to insert.
* @returns {string} The new, combined string.
*/
function insertAt(originalString, stringToInsert, index) {
if (index < 0 || index > originalString.length) {
throw new Error('Index is out of bounds.');
}
return originalString.slice(0, index) + stringToInsert + originalString.slice(index);
}
// Example Usage:
const sentence = "The quick fox jumps over the lazy dog.";
const correctedSentence = insertAt(sentence, ' brown', 9);
console.log(correctedSentence);
// Output: "The quick brown fox jumps over the lazy dog."
Conclusion
Inserting a string at a specific index is a common task with a clear, preferred solution in JavaScript.
- The
slice()method is the recommended best practice. It is readable, predictable, and efficient. The pattern isstr.slice(0, index) + subStr + str.slice(index). - Avoid more complex and less efficient alternatives like converting to an array to use
splice(). - While
substring()works for this specific task,slice()is generally considered the more robust tool for string extraction.