Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
How to Get the Middle Character from a string?

I am training on kata from CodeWars that can be found here https://www.codewars.com/kata/56747fd5cb988479af000028/train/javascript

I could not understand other solutions. My try is it:

const getMiddle = (s) => {
  let middle = ""
  for(let i = 0; i < s.length; i++) {
    if(s.length % 2 === 1) {middle = s[s.length-1/2]}
    if(s.length % 2 === 0) {middle = s[s.length-1/2-1] + s[s.length-1/2]}
  } return middle
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You're making this far more complicated than it needs to be.

You don't need a loop, since the length is not dependent on i.

Instead of checking whether the length is odd or even, you can just divide by 2 and round down.

function getMiddle(s) {
    return Math.floor(s.length / 2);
}
about 4 years ago · Juan Pablo Isaza Report

0

s.length / 2 will return number in floating point if the s length's is odd

console.log(5 / 2);
console.log(6 / 2);

You have to parse it to int either using parseInt, or there is a shortcut that you can use as

(s.length / 2 - 1) | 0

const a = 5 / 2;

console.log(parseInt(a));
console.log(a | 0);

const getMiddle = (s) => {
  let middle = "";

  if (s.length % 2 === 1) middle = [s[(s.length / 2) | 0]];
  else middle = [s[(s.length / 2 - 1) | 0], s[(s.length / 2) | 0]];

  return middle.join("");
};

console.log(getMiddle("A"));
console.log(getMiddle("HELMO"));
console.log(getMiddle("HELLO0"));

about 4 years ago · Juan Pablo Isaza Report

0

Do not iterate letters. You can simply do it for the even and odd lengths of strings.

const getMiddle = (s) => {
  return s[Math.floor(s.length/2)]
}

console.log(getMiddle("abc"));
console.log(getMiddle("abcd"));
console.log(getMiddle("abcde"));
console.log(getMiddle("abcdef"));
console.log(getMiddle("abcdefg"));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!