Names in inputs, with capital first letters ignoring(de,do,da,das, dos etc)!

Asked

Viewed 480 times

1

in which personal names wanted to leave it but organized, I have a script in which leaves the first uppercase letters of the name, but it does not ignore those of, dos, das, da etc, I wondered if it is possible to add this exception to the script!

function c(id) {
    var letra = document.getElementById(id).value;
    letra = letra.split("");
    var tmp = "";
    for (i = 0; i < letra.length; i++) {
        if (letra[i - 1]) {
            if (letra[i - 1] == " " || letra[i - 1] == ".") {
                letra[i] = letra[i].replace(letra[i], letra[i].toUpperCase());
            }
        } else {
            letra[i] = letra[i].replace(letra[i], letra[i].toUpperCase());
        }
        tmp += letra[i];
    }
    document.getElementById(id).value = tmp;
}
<input onkeyup="c('input-1')"  required class="inp_editar" type="text" name="nome_cont" id="input-1"/>

Obg!

  • Dei an answer about it. To prevent making large letter short words you need a list of them. You have a list?

  • basically it’s just the, the, and, the, the

1 answer

3


Developing further the other answer you can do it like this:

var ignorar = ["das", "dos", "e", "é", "do", "da", "de"];
function caixaAlta(string) {
    return String(string).replace(/([^A-zÀ-ú]?)([A-zÀ-ú]+)/g, function(match, separator, word) {
        if (ignorar.indexOf(word) != -1) return separator + word;
        return separator + word.charAt(0).toUpperCase() + word.slice(1);
    });
}

var testes = ['a música é universal', 'a democracia é de todos'].map(caixaAlta);
console.log(JSON.stringify(testes)); // ["A Música é Universal","A Democracia é de Todos"]

And when you find a word that’s not on the list, add.

jsFiddle: https://jsfiddle.net/LgLz5znq/


And to integrate that into your code you can do so:

HTML:

<input onkeyup="corrigirValor(this)" ...etc

notes that using the this I’m already passing the element itself, I don’t need to pass Ids.

Javascript:

function corrigirValor(el) {
    el.value = caixaAlta(el.value);
}

Example: https://jsfiddle.net/LgLz5znq/1/

  • 1

    Thanks friend, it worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.