Soy nuevo en JavaScript y tengo algunos problemas con este problema:
Construya una función llamada titleCase que tome una cadena de oraciones y le dé mayúsculas y minúsculas.
titleCase("this is an example") // Should return "This Is An Example" titleCase("test") // Should return "Test" titleCase("ir cool") // Should return "IR Cool" titleCase("WHAT HAPPENS HERE") // Should return "What Happens Here" titleCase("") // Should return "" titleCase("A") // Should return "A"Este es el código que he probado:
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(' '); } Está pasando todas las pruebas excepto la prueba de cadena vacía "" .
Tendrás que moverte:
if (text === "") { return "" }a la primera línea de la función.
Aquí hay una solución sencilla:
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("ir cool")); //should return "IR Cool" console.log(titleCase("WHAT HAPPENS HERE")); //should return "What Happens Here" console.log(titleCase("")); //should return "" console.log(titleCase("A")); //should return "A"Solo tiene que declarar el texto vacío como predeterminado en la función y agregar la condición if (text === "") { antes del ciclo for . Entonces, si el texto está vacío, antes de ejecutar el bucle for , devolverá "". Por favor revise el siguiente fragmento:
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"));No puede modificar un carácter con la notación [] .
Para reemplazar el primer carácter de una cadena, no haga
str[0] = str[0].toUppercase()pero
str = "X" + str.substr(1)Su función puede ser:
function titleCase(str) { return str.toLowerCase().replace(/(^|\s)[az]/g, (a)=>a.toUpperCase()); }Esta función:
[az] ) después de un espacio ( \s ) o el comienzo de la cadena ( ^ ) con su versión en mayúsculas.