Esto es lo que tengo. Cualquier sugerencia sería de gran ayuda. ¡Gracias!:
function fixGrammar(input) { for (let i = 0; i < input.length; i++) { if(i === 0){ input = input[i].toUpperCase() + input.slice(1); } if(input[i] === (/\s[i+ ]/g)) { let capitalize = input[i].toUpperCase() } if(input[i] === '.') { let afterPeriod = input[i+2]; afterPeriod.toUpperCase(); } } return input; } console.log(fixGrammar("there's something you learn in your first boot-camp. if they put you down somewhere with nothing to do, go to sleep — you don't know when you'll get any more." ))No puede comparar una letra con una expresión regular usando == y esperar encontrar una coincidencia. También esa expresión regular /\s[i+ ]/g buscaría un espacio en blanco seguido de un literal i o literal + o un espacio.
Puede usar una expresión regular para detectar las letras que deben escribirse en mayúscula y reemplazarlas con replace :
const fixGrammar = s => s.replace(/(?<=^|\. )\w/g, c => c.toUpperCase()); console.log(fixGrammar("there's something you learn in your first boot-camp. if they put you down somewhere with nothing to do, go to sleep — you don't know when you'll get any more." ));Soluciones de una sola línea FTW:
Sol 1:
input.split(". ").map( m => m[0].toUpperCase() + m.slice(1) // `m[0]` gets the first character, `m.slice(1)` skips the first character and collects the rest of them together. ).join(". ")Sol 2: O puede hacerlo más detallado:
input.split(". ").map( ([firstChar, ...restChars]) => firstChar.toUpperCase() + restChars.join("") // `restChars` would be an array of characters, so we are joining them to get the original substring ).join(". ")En el primer sol, m.slice(1) devolverá una cadena, pero si hiciera lo mismo con array, digamos ["a", "b", "c"].slice(1); devolvería una nueva matriz ["b", "c"].
PD: la input es la variable que tiene el valor de cadena. Puede usarlo dentro de su función fixGrammar . ¡La solución mencionada aquí asume que habría exactamente un espacio después del punto!
Divida en puntos con cualquier cantidad de espacios finales, escriba en mayúscula el primer carácter de cada oración y luego únase a la matriz en un punto y un espacio.
const paragraph = `there's something you learn in your first boot-camp. if they put you down somewhere with nothing to do, go to sleep — you don't know when you'll get any more.`; const capitalizeSentences = (str) => { return str .split(/\.[\s]+/) .map((sentence) => `${sentence[0].toUpperCase()}${sentence.slice(1)}`) .join('. '); }; console.log(capitalizeSentences(paragraph));