Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda