Search code examples
javascriptarrayslowercasecapitalization

How to change input.value to capitalize before submitting to array Javascript


I have a button that submits a input.value to the empty array.

The function is checking if there isnt' any matching names inside the array and throws the error if there is, but not if there are lowercase or uppercase letters.

I want this function to capitalize the input.value first letter, and lowercase the rest before submitting it into the array. So I want to easly check if there won't be two same names just written the other way.

Do you know how to make it work using vanilla JS?

const nameInput = document.getElementById('inputName');
let nameListDisplay = document.getElementById('nameListDisplay');
let assignmentDisplay = document.getElementById('assignmentDisplay');
let onlyLetters = '^[a-zżźćńłśąęóA-ZŻŹĆŃŁŚĄĘÓ ]+$';

let namesList = [];
    
function addName() {
        if (nameInput.value.match(onlyLetters)) {
            if (namesList.includes(nameInput.value)) {
                console.log('error');
            }
            else {
                console.log('name added');
                namesList.push(nameInput.value);
                nameInput.value = ''; 
                displayNames();
            }  
        }
        else {
            console.log('error');
        }
    };

Solution

  • This function will capitalize first letter and lower case the rest of the string.

    function toTitleCase(str) {
      return str.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
    }
    

    and then:

    if (nameInput.value.match(onlyLetters)) {
                if (namesList.includes(toTitleCase(nameInput.value))) { // here
                    console.log('name already exists');
                }
                else {
                    console.log('name added');
                    namesList.push(toTitleCase(nameInput.value)); // here
                    nameInput.value = ''; 
                    displayNames();
                }  
            }
            else {
                console.log('error');
            }
    }