OneCompiler

[Javascript] How to insert a sub string at a given index of a string?

I want to insert a substring at a given index, like I want to insert sample before test in the string This is a test message. How can I do that in Javascript?

1 Answer

4 years ago by

You can use either of the below methods to insert a substring at a given index:

let str= 'This is a test message';

//method: 1
const insertAt = (str, sub, pos) => `${str.slice(0, pos)}${sub}${str.slice(pos)}`;
console.log(insertAt(str, 'sample ', str.indexOf("test"))); 

//method: 2
console.log(str.split('test').join('sample test'));

Run here https://onecompiler.com/javascript/3xnrssz5j

4 years ago by Meera