How can I make the first letters of the capitalized words appear?

3

The fact is that I have this code and it only converts the first letter. The fact is that I want you to convert the first letters of each word and I do not 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);
    }
    
asked by Stewie 21.10.2017 в 20:49
source

4 answers

5

The shortest implementation to capitalize words within a string is the following using the Arrow functions of ES6:

'your string'.replace(/\b\w/g, l => l.toUpperCase())
// => 'Your String'

Implementation compatible with ES5:

'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 uppercase letter:

\ b matches a word limit (the beginning or end of the word);
\ w matches the following metacharacters [a-zA-Z0-9].

    
answered by 21.10.2017 в 20:56
2

Using, replace (), regular expressions and ES6 arrow functions

console.log('kdz stack overflow'.replace(/\b[a-z]/g,c=>c.toUpperCase()));
    
answered by 22.10.2017 в 19:46
1

Let's make a solution in Spanish with regular expressions.

  

About the letters of Spanish:
  For regular expressions in JavaScript, the ñ and the accents are not word characters 1 .
1 : Not included in \w , and therefore \b misses them


In JavaScript 2 , we have to match the previous character (or the beginning of the string) and include it in the replacement, followed by a lowercase letter.
2 : Because in JavaScript there are no backward inspections ( lookbehinds ), as there are in other dialects of regex.

To capitalize the lowercase at the beginning of each word:

const re = /(^|[^A-Za-zÁÉÍÓÚÜÑáéíóúüñ])([a-záéíóúüñ])/g;
texto.replace(re, function(match, caracterPrevio, minuscula) {
    return caracterPrevio + minuscula.toLocaleUpperCase(['es', 'gl', 'ca', 'pt', 'en']);
});


And, in addition, we can take to lowercase all the rest, doing:

  • that also matches initial capitals (not to replace),
  • and with intermediate capital letters (to lower case).


Solution:

function titleCase(texto) {
    const re = /(^|[^A-Za-zÁÉÍÓÚÜÑáéíóúüñ])(?:([a-záéíóúüñ])|([A-ZÁÉÍÓÚÜÑ]))|([A-ZÁÉÍÓÚÜÑ]+)/gu;
    return texto.replace(re,
        (m, caracterPrevio, minuscInicial, mayuscInicial, mayuscIntermedias) => {
            const locale = ['es', 'gl', 'ca', 'pt', 'en'];
            if (mayuscIntermedias)
                return mayuscIntermedias.toLocaleLowerCase(locale);
            return caracterPrevio
                 + (minuscInicial ? minuscInicial.toLocaleUpperCase(locale) : mayuscInicial);
        }
    );
}


Description:

/(^|[^A-Za-zÁÉÍÓÚÜÑáéíóúüñ])(?:([a-záéíóúüñ])|([A-ZÁÉÍÓÚÜÑ]))|([A-ZÁÉÍÓÚÜÑ]+)/gu

They are 2 alternatives in a OR : /1|2/gu

  • (^|[^A-Za-zÁÉÍÓÚÜÑáéíóúüñ])(?:([a-záéíóúüñ])|([A-ZÁÉÍÓÚÜÑ])) - INITIAL LETTER.

    • (^|[^A-Za-zÁÉÍÓÚÜÑáéíóúüñ]) - Start of the text or any character that is not alphabetic.
      It is the first group = > the callback is passed in the variable caracterPrevio .
    • (?:([a-záéíóúüñ])|([A-ZÁÉÍÓÚÜÑ])) - The first letter of the word, either:
      ([a-záéíóúüñ]) - lowercase letter = > is passed as variable minuscInicial , or% ([A-ZÁÉÍÓÚÜÑ]) - uppercase letter = > is passed as variable mayuscInicial .
  • ([A-ZÁÉÍÓÚÜÑ]+) - INTERMEDIATE CAPITAL LETTERS
    When it coincides with this part, it means that it did not coincide with the first one. Therefore, we know that it is not a letter at the beginning of a word, but an intermediate letter.

    • [A-ZÁÉÍÓÚÜÑ]+ matches 1 or more uppercase letters (not initials), so we can lower them to lowercase.
      It is the fourth group = > is passed as variable mayuscIntermedias .

  • Demo:

    //Leva a mayúsculas la primera letra de cada palabra
    function titleCase(texto) {
        const re = /(^|[^A-Za-zÁÉÍÓÚÜÑáéíóúüñ])(?:([a-záéíóúüñ])|([A-ZÁÉÍÓÚÜÑ]))|([A-ZÁÉÍÓÚÜÑ]+)/gu;
        return texto.replace(re,
            (m, caracterPrevio, minuscInicial, mayuscInicial, mayuscIntermedias) => {
                const locale = ['es', 'gl', 'ca', 'pt', 'en'];
                //Son letras mayúsculas en el medio de la palabra
                // => llevar a minúsculas.
                if (mayuscIntermedias)
                    return mayuscIntermedias.toLocaleLowerCase(locale);
                //Es la letra inicial de la palabra
                // => dejar el caracter previo como está.
                // => si la primera letra es minúscula, capitalizar
                //    sino, dejar como está.
                return caracterPrevio
                     + (minuscInicial ? minuscInicial.toLocaleUpperCase(locale) : mayuscInicial);
            }
        );
    }
    
    //Evento para mostrar el resultado cada vez que se ingresa un caracter
    document.getElementById('ingreso')
        .addEventListener('input',
            event => {
                document.getElementById('resultado')
                    .innerText = titleCase(event.target.value);
            }
        );
    <input type="text"
           id="ingreso"
           placeholder="Escribí texto para llevar a mayúsculas la primera letra de cada palabra"
           style="width:100%">
    <pre id="resultado">
        
    answered by 26.10.2017 в 23:28
    0

    Seeing the answers given, I'll give you a solution without using regex .

    Characteristics of the function:

    • You can pass a single word or a whole string
    • Respect tildes and umlauts
    • We do not use regex

    function capitalizarPalabras( val ) {
      
      return val.toLowerCase()
                .trim()
                .split(' ')
                .map( v => v[0].toUpperCase() + v.substr(1) )
                .join(' ');  
    }
    
    console.log( capitalizarPalabras( 'hola' ) );
    console.log( capitalizarPalabras( ' hola' ) ); // Empieza con un espacio
    console.log( capitalizarPalabras( 'hola mundo ' ) );
    console.log( capitalizarPalabras( 'ñoño óle' ) );
    console.log( capitalizarPalabras( '1 ñoño óle' ) );
    console.log( capitalizarPalabras( ' über öll mi au' ) );
    console.log( capitalizarPalabras( 'algun texto sin sentido. y este aún menos. ' ) );
        
    answered by 22.11.2017 в 16:00