JavaScript - Delete Character at a Given Position in a String
Last Updated : 21 Nov, 2024
Improve
These are the following ways to Delete Character at a Given Position in a String:
1. Using slice() Method
The slice() method allows you to extract portions of a string. By slicing before and after the target position, you can omit the desired character.
let str = "Hello GFG";
let idx = 5;
let res = str.slice(0, idx) + str.slice(idx + 1);
console.log(res);
Output
HelloGFG
2. Using substring() Method
The substring() method works similarly to slice, but does not support negative indices.
let str = "Hello GFG";
let idx = 5;
let res = str.substring(0, idx) + str.substring(idx + 1);
console.log(res);
Output
HelloGFG
3. Using Array Conversion
Convert the string into an array of characters, remove the character at the desired position using splice, and join the array back into a string.
let str = "Hello GFG";
let idx = 5;
let arr = str.split("");
arr.splice(idx, 1);
let res = arr.join("");
console.log(res);
Output
HelloGFG