7 kyu · reference

Get the Middle Character

FundamentalsStrings

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.

Examples:

"test" --> "es"
"testing" --> "t"
"middle" --> "dd"
"A" --> "A"

Solutions

01-solution.jsView on GitHub ↗
function getMiddle(s) {
	if (s.length == 1) {
		return s;
	}
	const middle = (s.length - 1) / 2;

	if (Number.isInteger(middle)) {
		return s[middle];
	} else {
		return s[Math.floor(middle)] + s[Math.ceil(middle)];
	}
}