JavaScript - Delete Character from JS String
Last Updated :
21 Nov, 2024
In JavaScript, characters can be deleted from the beginning, end, or any specific position in a string. JavaScript provides several methods to perform these operations efficiently.
Delete First Character
To remove the first character from a string, we can use methods like slice, substring, or regular expressions.
Example (Using slice):
JavaScript
let str = "Hello GFG";
let result = str.slice(1); // Removes the first character
console.log(result);
You can delete the character from the beginning of the given string using many other methods, refer to this article for more Methods.
Delete Last Character
To delete the last character from a string, methods like slice or substring are commonly used.
Example (Using slice):
JavaScript
let str = "Hello GFG";
let result = str.slice(0, -1); // Removes the last character
console.log(result);
You can delete the character from the end of the given string using many other methods, refer to this article for more Methods.
Delete Character at a Specific Position
To remove a character from a specific position, split the string into parts before and after the position and concatenate them.
Example (Using slice):
JavaScript
let str = "Hello GFG";
let position = 5;
let result = str.slice(0, position) + str.slice(position + 1);
console.log(result);
You can delete the character from the end of the given string using many other methods, refer to this article for more Methods.
Delete All Occurrence of a Character
Delete the given character's occurrence from the given string and print the new string.
Example (Regular Expression):
JavaScript
let str = "Geeks-for-Geeks";
let ch = "-";
let regex = new RegExp(ch, 'g');
let res = str.replace(regex, '');
console.log(res);
You can delete all occurrence of character from the given string using many other methods, refer to this article for more Methods.