Explain Codes LogoExplain Codes Logo

Inserting string at a specific position in a string using JavaScript

javascript
prompt-engineering
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Jan 15, 2025
TLDR

Implement string insertion at a specific index using the substring method in JavaScript:

const swiftInsert = (original, index, insert) => original.substring(0, index) + insert + original.substring(index); console.log(swiftInsert("Hello World", 5, " lovely")); // Output: "Hello lovely World"

The swiftInsert function swiftly integrates insert within original at the specified index.

Custom splice method for strings

JavaScript strings lack a splice method inherently. However, we can extend the String prototype to include a custom splice method:

String.prototype.splice = function(start, newSubStr) { return this.slice(0, start) + newSubStr + this.slice(start); }; console.log("Hello World".splice(5, " lovely")); // Output: "Hello lovely World"

The splice method, now effective on strings, seamlessly inserts newSubStr at the defined start position, much like splicing an array.

Negative index handling

To accommodate splice calls with negative indices, we adjust the splice method:

String.prototype.splice = function(start, newSubStr) { if (start < 0) { start = this.length + start; start = start < 0 ? 0 : start; // No negative train rides allowed } return this.slice(0, start) + newSubStr + this.slice(start); }; console.log("Hello World".splice(-6, " lovely"));

Our splice method now takes us on a slightly different journey, accepting negative indexes and still arriving at the correct destination.

Template literals for multiple insertions

For those instances when you need to make multiple insertions at once and want to keep your code clean, we can employ template literals:

const multiInsert = (str, ...insertInstructions) => { return insertInstructions.reduce((current, instruction) => { const [position, insert] = instruction; return current.splice(position, insert); }, str); }; console.log(multiInsert("Hello World", [5, " lovely"], [13, " place"])); // Output: "Hello lovely World place"

The multiInsert function now offers first-class tickets for multiple insertions, dynamically adjusting indexes as the string length shifts due to previous insertions.

Validate all the things!

Always ensure to validate the index and insertion strings to prevent any unintended consequences (such as a train wreck):

// Add this inside our splice or insert function if (typeof index !== 'number' || index < 0 || index > str.length) { throw new Error('Ensure index is a non-negative integer within the string length, or else...'); }

Edge cases, even those at the boundaries, remain intact without causing any chaos.

Visualising string characters

Picture a string like a train (🚂) where each carriage is a character:

Original String: 🚂🅰️🅱️🅲️🅳️🅴️

You want to insert a 'X' at position 3:

Appending 🚂🅰️🅱️🆇🅲️🅳️🅴️

Voila! All passengers remain happy on this exhilarating journey.

Search and Insert

The insertAfter() function uses indexOf() to find a keyword and inserts your string right after it:

const insertAfter = (str, keyword, insert) => { const index = str.indexOf(keyword); if (index !== -1) { return str.splice(index + keyword.length, insert); } return str; // Output original string if keyword not found, just like "Where's Waldo?" }; console.log(insertAfter("Hello World", "Hello", " lovely")); // Output: "Hello lovely World"

Styling for clarity

When debugging, or going for Edutainment, make your console output snazzy:

console.log(`%c${swiftInsert("Hello World", 5, " lovely")}`, 'color: purple; font-weight: bold;');

Our good old palconsole.log is now a runway model exuding style and color.