JavaScript - Insert Character at a Given Position in a String
Last Updated : 21 Nov, 2024
Improve
These are the following approaches to insert a character at a given position:
1. Using String Concatenation with Slicing
Split the string into two parts—before and after the position—and concatenate the character in between.
let str = "Hello GFG";
let ch = "!";
let idx = 5;
let res = str.slice(0, idx) + ch + str.slice(idx);
console.log(res);
Output
Hello! GFG
2. Using Template Literals
Using template literals, we can easily insert a character at a specified position in a string by breaking the string into two parts and injecting the new character between them.
let str = "Hello GFG";
let ch = "!";
let idx = 5;
let res = `${str.slice(0, idx)}${ch}${str.slice(idx)}`;
console.log(res);
Output
Hello! GFG
3. Using Arrays for Insertion
Convert the string into an array, insert the character at the desired position using array manipulation, and then join the array back into a string.
let str = "Hello GFG";
let ch = "!";
let idx = 5;
let arr = str.split("");
arr.splice(idx, 0, ch);
let res = arr.join("");
console.log(res);
Output
Hello! GFG