如何在JavaScript中实现句子的标题大小写转换?
Complete Title Case Conversion Implementation in JavaScript
Here's the full working implementation of your function (renamed to toTitleCase for clarity—you can revert to toUpper if you prefer) that converts a sentence to title case, building on your initial code:
<html> <head> <!--Wei Wu Section A--> <title>This is the 4th extra credit</title> </head> <body> <script type="text/javascript"> function toTitleCase(stringFromUser) { // Split input into an array of individual words const arrayOfStrings = stringFromUser.split(" "); // Loop through each word to adjust capitalization for (let i = 0; i < arrayOfStrings.length; i++) { const word = arrayOfStrings[i]; // Skip empty strings caused by multiple consecutive spaces if (word.length === 0) continue; // Check if first character is a lowercase letter (ASCII 97-122) if (word.charCodeAt(0) >= 97 && word.charCodeAt(0) <= 122) { // Capitalize first character + convert rest to lowercase for consistency arrayOfStrings[i] = word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); } else { // If first character is already uppercase/non-alphabetic, normalize the rest to lowercase arrayOfStrings[i] = word.charAt(0) + word.slice(1).toLowerCase(); } } // Join processed words back into a single sentence return arrayOfStrings.join(" "); } // Example test run const sampleInput = "hello WORLD! this is a mixed-case sentence."; const titleCaseResult = toTitleCase(sampleInput); console.log(titleCaseResult); // Output: "Hello World! This Is A Mixed-Case Sentence." </script> </body> </html>
Key Improvements & Explanations:
- Completed Character Check: Finished the original
charCodeAtlogic to detect lowercase first letters and convert them to uppercase. - Consistent Formatting: Converts the rest of each word to lowercase, ensuring uniform title case even if the input has random uppercase letters.
- Handles Edge Cases: Skips empty strings from multiple spaces and preserves non-alphabetic first characters (like exclamation marks or numbers) while normalizing the rest of the word.
Optional Enhancements:
If you want to follow strict traditional title case rules (e.g., skip capitalizing small words like "the", "and", "a"), you can add a check against a list of excluded words before processing:
const excludedWords = ["the", "and", "a", "an", "of", "for"]; // Inside the loop: if (!excludedWords.includes(word.toLowerCase())) { // Apply capitalization logic here }
内容的提问来源于stack exchange,提问作者Wei WU
相关产品推荐
相关产品推荐

