Let's see an example on how to remove the middle char of a string in JavaScript:
javascript// We want to remove 'e' and get 'Elna' let string = 'Elena'; // Odd strings → middle point will be an integer // Even strings → middle point will be a decimal let middle = (string.length - 1)/2; // We filter those indexes that are different from the middle point // Notice how for decimal numbers, we won't filter anything, because integer !== decimal let sliced = [...string].filter((char, index) => index !== middle).join(''); console.log(sliced); // Elna
In one line of code:
javascriptlet sliced = [...string].filter((char, index) => index !== (string.length - 1)/2).join('');
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.