求助:实现带例外规则的输入框标题大小写转换的JavaScript方案
标题大小写实时转换实现方案
需求要点
- 针对ID为
title的输入框,实时输入时自动转换文本为标题大小写(也支持失焦/提交前触发) - 指定例外词(如
and、the、in)保持小写 - 句首单词强制大写
- 保留全大写的缩写词(如
USA、NATO)
输入字段HTML
<input name="title" id="title" autocomplete="off" type="text" value="" class="dev-input aa-form-text">
JavaScript实现代码
可直接嵌入页面,也可保存为外部JS文件引入:
document.addEventListener('DOMContentLoaded', function() { const titleInput = document.getElementById('title'); // 自定义例外词列表,可按需增删 const lowercaseExceptions = new Set(['and', 'the', 'in', 'on', 'of', 'for', 'a', 'an']); function convertToTitleCase(text) { if (!text) return text; // 分割单词并保留连续空格,避免格式丢失 const words = text.split(/(\s+)/); return words.map((word, index) => { // 跳过纯空格项 if (/\s+/.test(word)) return word; // 句首第一个非空格单词,强制首字母大写 if (index === 0 || (index > 0 && /^\s+$/.test(words[index-1]))) { return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); } // 长度≥2的全大写单词,判定为缩写并保留原样 if (word.length >= 2 && word === word.toUpperCase()) { return word; } // 例外词统一转小写 if (lowercaseExceptions.has(word.toLowerCase())) { return word.toLowerCase(); } // 普通单词首字母大写、其余小写 return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); }).join(''); } function handleInput() { const cursorPos = titleInput.selectionStart; const originalVal = titleInput.value; const convertedVal = convertToTitleCase(originalVal); // 仅在值变化时更新,避免无效操作影响光标 if (convertedVal !== originalVal) { titleInput.value = convertedVal; // 恢复光标位置,优化输入流畅度 titleInput.setSelectionRange(cursorPos, cursorPos); } } // 绑定实时输入事件,实现即时转换 titleInput.addEventListener('input', handleInput); // 可选:失焦时再触发一次,确保转换完全 titleInput.addEventListener('blur', handleInput); });
额外说明
- 体验优化:转换过程中会保存并恢复光标位置,避免输入卡顿
- 扩展性:
lowercaseExceptions集合可根据需求自由添加需要小写的词汇 - 兼容场景:既支持实时输入转换,也可通过
blur事件在失焦时做最终校验
内容的提问来源于stack exchange,提问作者Neon
相关产品推荐
相关产品推荐

