将输入字段更改为标题大小写(但有例外)的代码

问题描述 投票:0回答:1
我知道这里有几种变体,但我找不到一个可以做我想要的事情。我需要在通过 onkeup、keydown 或单击字段外(或任何类似方法)提交表单之前将输入字段中的文本更新为标题大小写。最好是输入文本。

我还需要一些例外,例如 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 文件),那就太好了。

javascript input title-case
1个回答
0
投票
有这样的事吗?

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">

© www.soinside.com 2019 - 2024. All rights reserved.