EN
JavaScript - remove character from string at specific index
0 points
In this article, we would like to show you how to remove a character from a string at a specific index in JavaScript.
Quick solution:
xxxxxxxxxx
1
let text = 'ABC';
2
const index = 1;
3
4
text = text.substring(0, index) + text.substring(index + 1);
5
6
console.log(text);
Note:
This approach doesn't remove the original string, it makes a copy ignoring the given character and overwriting the text.
In this example, we create a reusable function that takes 2 arguments:
text
- the string we want to remove a character from,index
- the index we want to remove.
xxxxxxxxxx
1
const removeCharacter = (text, index) => {
2
return text.substring(0, index) + text.substring(index + 1);
3
};
4
5
6
// Usage example:
7
8
const text = 'ABC';
9
10
console.log(removeCharacter(text, 0));
11
console.log(removeCharacter(text, 1));
12
console.log(removeCharacter(text, 2));
Output:
xxxxxxxxxx
1
BC
2
AC
3
AB