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:
// ONLINE-RUNNER:browser;
let text = 'ABC';
const index = 1;
text = text.substring(0, index) + text.substring(index + 1);
console.log(text);
Note:
This approach doesn't remove the original string, it makes a copy ignoring the given character and overwriting the text.
Reusable function
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.
// ONLINE-RUNNER:browser;
const removeCharacter = (text, index) => {
return text.substring(0, index) + text.substring(index + 1);
};
// Usage example:
const text = 'ABC';
console.log(removeCharacter(text, 0));
console.log(removeCharacter(text, 1));
console.log(removeCharacter(text, 2));
Output:
BC
AC
AB