You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 charCodeAt logic 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:08:43