Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda