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
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays
- JavaScript – Convert an array to an objectThere are many ways to convert an array to an object in JavaScript. Let’s explore some of the common approaches – Using reduce() In the… Read more: JavaScript – Convert an array to an object
- JavaScript – Shuffle an array in a random orderTo shuffle an array in random order in JavaScript, you can use the sort() function with Math.random() or use the map() & sort() function. Let’s… Read more: JavaScript – Shuffle an array in a random order