Code challenge: write a function that gets the middle letter(s) of a string of even or odd numbered letters, as a ternary operator.
My function is working for odd numbers. But it does not work for even numbers - it seems to be skipping letters.
eg.
getMiddle("testing") // the output is "t", this is correct.
getMiddle("test") // the output is "et", it should be "es".
my code:
function getMiddle(str) {
return str.length % 2 === 0 ? str[str.length/2 - 1] + str[str.length/2 + 1] : str[Math.floor(str.length/2)];
}
When the length is is even, you want the 2 characters which are at the middle. You do that by taking the length of the string and divide it by 2.
That index in a zero based array will be the s
.If you subtract 1 from the index, it will be the e
. When you add +1, you get the t
In your code, you concatenate the index -1 and the index +1 leading to et
You should omit the + 1 in str[str.length/2 + 1]
like:
function getMiddle(str) {
return str.length % 2 === 0 ? str[str.length / 2 - 1] + str[str.length / 2] : str[Math.floor(str.length / 2)];
}
function getMiddle(str) {
return str.length % 2 === 0 ? str[str.length / 2 - 1] + str[str.length / 2] : str[Math.floor(str.length / 2)];
}
console.log(getMiddle("testing"));
console.log(getMiddle("test"));
console.log(getMiddle("testtest"))