简体   繁体   English

如何在提交到数组 Javascript 之前将 input.value 更改为大写

[英]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.我有一个按钮将 input.value 提交到空数组。

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.我希望此函数将 input.value 的第一个字母大写,并将其余字母小写,然后再将其提交到数组中。 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?你知道如何使用 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');
        }
    };

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');
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM