Inserting string at position x of another string using Javascript


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 −

Example

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

Output

This will give the output −

HelloTest World

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

raja
Published on 02-Dec-2019 06:51:19
Advertisements