Skip to content

Instantly share code, notes, and snippets.

@0D1NTR33
Last active October 28, 2022 21:43
Show Gist options
  • Save 0D1NTR33/e65a5b18e7ce5a448dfe6ab80cdb4304 to your computer and use it in GitHub Desktop.
Save 0D1NTR33/e65a5b18e7ce5a448dfe6ab80cdb4304 to your computer and use it in GitHub Desktop.
Get the Middle Character (JavaScript)
// Awesome
function getMiddle(s)
{
return s.substr(Math.ceil(s.length / 2 - 1), s.length % 2 === 0 ? 2 : 1);
}
// Usual
function GetMiddle(s)
{
var middle = Math.floor(s.length/2);
if (s.length % 2 == 0)
return s[middle-1] + s[middle];
else
return s[middle];
}
/*
Kata.getMiddle("test") should return "es"
Kata.getMiddle("testing") should return "t"
Kata.getMiddle("middle") should return "dd"
Kata.getMiddle("A") should return "A"
*/
@alyson-b69
Copy link

Thanks for the explications :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment