DEV Community

Madalina Pastiu
Madalina Pastiu

Posted on

Get the Middle Character

Instructions:
You are going to be given a non-empty string. Your job is to return the middle character(s) of the string.
If the string's length is odd, return the middle character.
If the string's length is even, return the middle 2 characters.

Thoughts:

  1. I check the condition of the string to be even or odd: s.length % 2 === 0 2.Function of that I return 2 middle letters for even and 1 middle letter for odd.

Solution:

function getMiddle(s) {
 return s.length % 2 === 0 ? s.slice(s.length/2-1, s.length/2 + 1) : s[Math.floor(s.length/2)];
}
Enter fullscreen mode Exit fullscreen mode

This is a CodeWars Challenge of 7kyu Rank (https://www.codewars.com/kata/56747fd5cb988479af000028/train/javascript)

Top comments (0)