Inserting string at position x of another string using Javascript

JavascriptFront End TechnologyObject Oriented Programming

Javascript does not give a direct way to achieve this. For this, we can use the slice method. The slice method extracts a section of a string and returns a new string.

To insert a string at a position x of another string, we can write the following function −


function insertAtX(str1, str2, x) {
   return `${str1.slice(0, x)}${str2}${str1.slice(x)}`
console.log(insertAtX("Hello World", "Test", 5));


This will give the output −

HelloTest World

This doesn't handle edge cases. You can add handling for those according to need.

Updated on 02-Dec-2019 06:51:39