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

361
Vistas
How do I solve this JavaScript titlecase problem with an empty string?

I'm new to JavaScript and am having a bit of trouble with this problem:

Construct a function called titleCase that takes a sentence string and gives it title casing.

titleCase("this is an example") // Should return "This Is An Example"

titleCase("test") // Should return "Test"

titleCase("i r cool") // Should return "I R Cool"

titleCase("WHAT HAPPENS HERE") // Should return "What Happens Here"

titleCase("") // Should return ""

titleCase("A") // Should return "A"

This is the code I've tried:

const titleCase = function(text) {
  text = text.split(' ');

  for (let i = 0; i < text.length; i++) {
    text[i] = text[i].toLowerCase().split('');
    text[i][0] = text[i][0].toUpperCase();
    text[i] = text[i].join('');
  }

  if (text === "") {
    return ""
  }

  return text.join(' ');
}

It is passing all tests except for the empty string "" test.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You will need to move:

 if (text === "") {
   return ""
 } 

to the first line of the function.

Here is a straightforward solution:

function titleCase(s){
   let r="";
   for (let i=0; i<s.length; i++) r+=(i==0 || s[i-1]==" ")?s[i].toUpperCase():s[i].toLowerCase();
   return r;
}
console.log(titleCase("helLo tHERE!"));
console.log(titleCase("this is an example")); //should return "This Is An Example"
console.log(titleCase("test")); //should return "Test"
console.log(titleCase("i r cool")); //should return "I R Cool"
console.log(titleCase("WHAT HAPPENS HERE")); //should return "What Happens Here"
console.log(titleCase("")); //should return ""
console.log(titleCase("A")); //should return "A"

about 4 years ago · Juan Pablo Isaza Denunciar

0

You just have to declare text empty as default in the function and add the if (text === "") { condition before the for loop. So if the text is empty then before executing the for loop it will return "". Please check the following snippet:

const titleCase = function(text = '') {
    if (text === "") {
       return ""
     }
  text = text.split(' ');

  for (let i = 0; i < text.length; i++) {
    text[i] = text[i].toLowerCase().split('');
    text[i][0] = text[i][0].toUpperCase();
    text[i] = text[i].join('');
  }

  return text.join(' ');
}

console.log(titleCase());
console.log(titleCase("Hello"));
console.log(titleCase("Hello World"));

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can’t modify a character with the [] notation.

To replace the first character of a string, don't do

str[0] = str[0].toUppercase()

but

str = "X" + str.substr(1)

Your function can be:

function titleCase(str) {
  return str.toLowerCase().replace(/(^|\s)[a-z]/g, (a)=>a.toUpperCase());
}

This function will:

  • convert all to lower case
  • then use a regular expression to replace letters ([a-z]) following a space (\s) or the beginning of the string (^) with its uppercase version.
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