JavaScript – Get the Middle Character

In this post, we will solve the problem of returning the middle character(s) of the word. If the word’s length is odd, return the middle character. If the word’s length is even, return the middle 2 characters.

const getMiddle = str => {
  const middle = Math.floor(str.length / 2);
  
  // Check if the length is even
  if (str.length % 2 === 0) {
    return str[middle - 1] + str[middle];
  } else {
    return str[middle];
  }
};
console.log(getMiddle('test')); //es
console.log(getMiddle('testing')); //t
console.log(getMiddle('middle')); //dd
console.log(getMiddle('A')); //A

This function calculates the middle index of the string. If the length of the string is even, it returns the two middle characters; otherwise, it returns the single middle character.

Similar Reads