我还需要一些例外,例如 and、the、in、but、on、to 等单词要小写。
我仍然需要在句子开头将任何单词大写。在理想的世界中,脚本始终将 USA、NATO、NFL、NASA 等单词大写(或者只允许按原样输入这些单词)。
字段输入HTML是
<input name="title" id="title" autocomplete="off" type="text" value="" class="dev-input aa-form-text">
如果这是通过 Javascript 完成的,我可以将其放置在页面上(或外部 .JS 文件),那就太好了。
const exceptions = ['and', 'the', 'in', 'but', 'on', 'to', 'a', 'an', 'for', 'nor', 'with'];
const acronyms = ['USA', 'NATO', 'NFL', 'NASA'];
const toTitleCase = (str) => {
return str.split(' ').map((word, index) => {
const lowerCaseWord = word.toLowerCase();
if (acronyms.includes(word.toUpperCase())) {
return word.toUpperCase();
}
if (exceptions.includes(lowerCaseWord) && index !== 0) {
return lowerCaseWord;
}
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}).join(' ');
};
const handleInput = (event) => {
const inputField = event.target;
const cursorPosition = inputField.selectionStart; // Save cursor position
inputField.value = toTitleCase(inputField.value);
inputField.setSelectionRange(cursorPosition, cursorPosition); // Restore cursor position
};
document.getElementById('title').addEventListener('input', handleInput);
<input name="title" id="title" autocomplete="off" type="text" value="" class="dev-input aa-form-text">