Get the Middle Character
Madalina Pastiu

Madalina Pastiu @maddiepst

Joined:
Mar 3, 2025

Get the Middle Character

Publish Date: Apr 24
0 0

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)

Comments 0 total

    Add comment