请求将输入框首句大写JS代码修改为每个单词首字母大写
Hey there! I've adjusted your code to capitalize the first letter of every word instead of just the first word in the input. Here's the revised version, along with breakdowns of the changes:
Revised Code
<script type='text/javascript'>//<![CDATA[ $(window).load(function(){ $(document).ready(function() { $('input').on('keydown', function(event) { // Check if we're typing a letter without modifier keys const isLetter = event.keyCode >= 65 && event.keyCode <= 90; const noModifiers = !(event.shiftKey || event.ctrlKey || event.metaKey || event.altKey); // Identify if we're at the start of a new word: either input start, or right after a space const isWordStart = this.selectionStart === 0 || (this.selectionStart > 0 && this.value.charAt(this.selectionStart - 1) === ' '); if (isLetter && noModifiers && isWordStart) { event.preventDefault(); // Convert the typed letter to uppercase const char = String.fromCharCode(event.keyCode).toUpperCase(); const currentValue = this.value; // Insert the uppercase letter at the correct cursor position const newValue = currentValue.slice(0, this.selectionStart) + char + currentValue.slice(this.selectionEnd); $(this).val(newValue); // Move cursor to right after the uppercase letter this.setSelectionRange(this.selectionStart + 1, this.selectionStart + 1); } }); }); });//]]> </script>
Key Changes Explained
- Word Start Detection: Added the
isWordStartcheck to recognize when we're at the beginning of a new word — either the very start of the input, or immediately after a space. This replaces the original logic that only checked for the input's first position. - Dynamic Value Insertion: Instead of prepending the uppercase letter to the entire input, we now split the current value at the cursor position, insert the uppercase letter, and recombine. This works even if the user is typing in the middle of the input.
- Cursor Position Fix: Updated the cursor placement to move right after the uppercase letter, so typing flows naturally after capitalizing a word's first letter.
Bonus: Support More Word Separators
If you want to capitalize after other word separators (like hyphens - or underscores _), adjust the isWordStart line to use a regex that matches those characters:
const isWordStart = this.selectionStart === 0 || (this.selectionStart > 0 && /[\s\-_]/.test(this.value.charAt(this.selectionStart - 1)));
内容的提问来源于stack exchange,提问作者Cody Coderson
相关产品推荐
相关产品推荐

