To insert a string at a specific index, you have to extract two substrings:
str.slice(0, index)
.str.slice(index)
.Once you have the substrings, simply use template literal or addition operator (+) to insert the string between the two substrings.
str.slice(0, index) + "string to be inserted" + str.slice(index) `${str.slice(0, index)}string to be inserted${str.slice(index)}`
Let's check out the code to insert string at a specific index position:
let str = "React Vue"; let index = 5; let result = str.slice(0, index) + " Angular" + str.slice(index); console.log(result); //"React Angular Vue" result = `${str.slice(0, index)} Angular${str.slice(index)}`; console.log(result); //"React Angular Vue"
Note: String in JavaScript follows zero-based indexing, which means the first character is at 0th position, and the last character is at "string.length - 1
".
The slice() method takes two parameters:
You can also use the substring() method to achieve the same result.
let str = "React Vue"; let index = 5; let result = str.substring(0, index) + " Angular" + str.substring(index); console.log(result); //"React Angular Vue" result = `${str.substring(0, index)} Angular${str.substring(index)}`; console.log(result); //"React Angular Vue"