Question:
The fact is that I have this code and it only converts me the first letter. The point is that I want to convert the first letters of each word and I don't know how to do it.
document.write("Nombre y apellidos<input type='text' id='datos'><br>");
document.write("<input type='button' value='Convertir' onclick='mostrarPalabra()'><br>");
function mostrarPalabra() {
var datos = document.getElementById('datos').value;
datos = convertir(datos.toLowerCase());
console.log(datos);
}
function convertir(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
Answer:
The shortest implementation for capitalizing words within a string is as follows using the ES6 Arrow functions:
'your string'.replace(/\b\w/g, l => l.toUpperCase())
// => 'Your String'
ES5 compliant implementation:
'your string'.replace(/\b\w/g, function(l){ return l.toUpperCase() })
// => 'Your String'
The regular expression matches the first letter of each word within the given string and transforms only that letter to uppercase:
\ b matches a word boundary (the beginning or end of the word);
\ w matches the following metacharacters [a-zA-Z0-9].