Languages
[Edit]
EN

JavaScript - remove character from string at specific index

0 points
Created by:
a_horse
538

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:

  1. text - the string we want to remove a character from,
  2. 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

References

  1. String.prototype.substring() - JavaScript | MDN

Alternative titles

  1. JavaScript - remove character from text at specified position
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join