Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put the first letter capitalized and the rest lowercase?

1) I'm trying to apply the first letter in uppercase and the other as lowercase. If the user write in the input, it should automatically transform. Examples:

"isaac guilherme araújo" to "Isaac Guilherme Araújo"

"iSAAC guILHErme aRAÚJO" to "Isaac Guilherme Araújo"

2) In Brazil there are names with connectives. Examples: "das" "da" "dos" "do" "de" "e".

Carlos Eduardo Julio dos Santos

Carlos Eduardo dos Santos e Silva

Carlos Eduardo da Silva

3) I am having this problem to work with the name fields. With the following code, i could apply the first letter in uppercase, but the others as lowercase i couldn't. Then, according to problem number 2, if I write:

value entered: "douglas de oliveira júnior"

should be: "Douglas de Oliveira Júnior"

shouldn't: "douglas de Oliveira Júnior". //value shown with current code

function contains(str, search){
 if(str.indexOf(search) >= 0){
   return true;
 } else {
   return false;
 }
}

$.fn.capitalize = function(str) {
    $.each(this, function() {
        var split = this.value.split(' ');
        for (var i = 0, len = split.length; i < len; i++) {
            var verify = (split[len - 1] == "D" || split[len - 1] == "d") && (str == "e" || str == "E") || (str == "o" || str == "O");
            if (verify == false) {
                if ( contains(split[i], 'de') == false && contains(split[i], 'do') == false) {
                    split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
                }
            }
        }
        this.value = split.join(' ');
    });
    return this;
};

$(".capitalize").keypress(function(e) {
    var str = String.fromCharCode(e.which);
    $(this).capitalize(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Nome: </label>
<input type="text" id="nome" name="nome" class="form-control input-sm capitalize">

I'm a new member here on Stackoverflow and I apologize for the mistakes, I am learning javascript. Thank you!

like image 782
Paulo Pitta Avatar asked Sep 08 '17 18:09

Paulo Pitta


People also ask

How do you capitalize the first letter and lowercase rest?

To capitalize the first letter of a string and lowercase the rest, use the charAt() method to access the character at index 0 and capitalize it using the toUpperCase() method. Then concatenate the result with using the slice() method to to lowercase the rest of the string.

How do I make the first letter capital and rest lowercase in Excel?

In cell B2, type =PROPER(A2), then press Enter. This formula converts the name in cell A2 from uppercase to proper case. To convert the text to lowercase, type =LOWER(A2) instead. Use =UPPER(A2) in cases where you need to convert text to uppercase, replacing A2 with the appropriate cell reference.

How do you capitalize the first and last letter of a string?

Use list slicing and str. upper() to capitalize the first letter of the string. Use str. join() to combine the capitalized first letter with the rest of the characters.

How do you capitalize the first character of a string to uppercase letter and lowercase all other characters?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.


3 Answers

This solution also fixes connectives in uppercase, such as carlos DE silva.
Try it with the snippet below :)

var connectives = {
    das: true,
    da: true,
    dos: true,
    do: true,
    de: true,
    e: true
};

function capitalize(str) {
    return str
        .split(" ")
        .map(function(word) {
            return !connectives[word.toLowerCase()]
                ? word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
                : word.toLowerCase();
        })
        .join(" ");
};

$(".capitalize").keyup(function() {
    var cursorStart = this.selectionStart;
    var cursorEnd = this.selectionEnd;
    var capitalizedString = capitalize($(this).val());

    $(this).val(capitalizedString);
    this.setSelectionRange(cursorStart, cursorEnd);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Nome: </label>
<input type="text" id="nome" name="nome" class="form-control input-sm capitalize">
like image 95
Borja Canseco Avatar answered Nov 05 '22 20:11

Borja Canseco


You could use a format function that capitalizes all words except those provided in a whitelist. Then format the input value whenever the user presses a key (doesn't work well if the user moves the input cursor around though):

function format(string, noCapList=[]) {
  const words = string.toLowerCase().split(' ');
  return words.map((word) => {
    if(!word.length || noCapList.includes(word)) {
      return word;
    } else {
      return word[0].toUpperCase() + word.slice(1);
    }
  }).join(' ');
}

const input = document.querySelector('input');
input.addEventListener('keyup', () => {
  input.value = format(input.value, ["das", "da", "dos", "do", "de", "e"]);
});
<input/>

It looks like the issue with your code is in how you're formatting the input. I'm not 100% sure I understood the question, but this format function provides the output you were looking for.

like image 37
SimpleJ Avatar answered Nov 05 '22 22:11

SimpleJ


for simplicity I used npm lodash

https://lodash.com/docs/4.17.11#capitalize

    const _ = require('lodash');
    const connectives = {
               das: true,
               da: true,
               dos: true,
               do: true,
               de: true,
               e: true
                     };


    const nameToCapitalize = str.split(' ').map(word => connectives[word] ? 
    word.toLowercase : _.capitalize(word)).join(' ');
like image 32
chaimm Avatar answered Nov 05 '22 20:11

chaimm