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

如何用JavaScript实现句子大小写规范化?支持特殊字符且无jQuery依赖

Solution for Context-Aware Word Case Normalization (No jQuery)

Got it, let's solve this problem where we need to normalize a specific word's case to match the overall style of a sentence—whether it's all lowercase, all uppercase, title case, or a mixed dominant-case scenario. Plus, we'll make sure it works with accented characters like ñ and ä, using pure vanilla JS.

Step 1: Detect the Sentence's Case Mode

First, we need a helper function to figure out what case style the sentence is using. This covers all common scenarios:

  • All uppercase
  • All lowercase
  • Title Case (each word starts with a capital letter)
  • Mixed dominant case (more uppercase than lowercase, or vice versa)
function getCaseMode(str) {
  // Extract only letter characters (ignore spaces, punctuation, etc.)
  const letters = str.replace(/[^a-zA-ZÀ-ÿ]/g, '');
  if (!letters) return 'mixed'; // Edge case: no letters in the string

  const isAllUpper = letters === letters.toUpperCase();
  const isAllLower = letters === letters.toLowerCase();

  if (isAllUpper) return 'upper';
  if (isAllLower) return 'lower';

  // Check for Title Case (each word's first letter is uppercase, rest lowercase)
  const isTitleCase = str.split(/\s+/).every(word => {
    const wordLetters = word.replace(/[^a-zA-ZÀ-ÿ]/g, '');
    if (!wordLetters) return true; // Skip empty words or words with no letters
    return wordLetters[0] === wordLetters[0].toUpperCase() && 
           wordLetters.slice(1) === wordLetters.slice(1).toLowerCase();
  });

  if (isTitleCase) return 'title';

  // For mixed cases, determine dominant case (more uppercase or lowercase letters)
  const upperCount = letters.split('').filter(c => c === c.toUpperCase()).length;
  return upperCount / letters.length > 0.5 ? 'upper-dominant' : 'lower-dominant';
}

Step 2: Normalize the Target Word

Next, the core function that takes your sentence and target word, then adjusts the word's case to match the sentence's style. It uses regex to find the target word (case-insensitive) and replaces it based on the detected case mode.

function normalizeTargetWord(sentence, targetWord) {
  const caseMode = getCaseMode(sentence);
  const targetLower = targetWord.toLowerCase();
  // Regex to match the target word as a whole word (case-insensitive)
  const targetRegex = new RegExp(`\\b${targetLower}\\b`, 'gi');

  return sentence.replace(targetRegex, match => {
    switch(caseMode) {
      case 'upper':
      case 'upper-dominant':
        return match.toUpperCase();
      case 'lower':
      case 'lower-dominant':
        return match.toLowerCase();
      case 'title':
        // Convert to Title Case: first letter uppercase, rest lowercase
        return match.charAt(0).toUpperCase() + match.slice(1).toLowerCase();
      default:
        return match; // Fallback: keep the original match if mode is unknown
    }
  });
}

Test It With Your Examples

Let's run through the sentences you provided to see how it works:

Example 1: Mixed Title Case Sentence

const sentence1 = "You are not the Intended recipient.";
console.log(normalizeTargetWord(sentence1, "intended"));
// Output: "You are not the Intended recipient." (matches Title Case style)

Example 2: All Uppercase Sentence

const sentence2 = "YOU ARE NOT THE INTENDED RECIPIENT.";
console.log(normalizeTargetWord(sentence2, "intended"));
// Output: "YOU ARE NOT THE INTENDED RECIPIENT." (stays all uppercase)

Example 3: Mixed Uppercase-Dominant Sentence

const sentence3 = "YOU ARE NOT THE intended RECIPIENT.";
console.log(normalizeTargetWord(sentence3, "intended"));
// Output: "YOU ARE NOT THE INTENDED RECIPIENT." (converts to uppercase to match dominant style)

Example 4: All Lowercase Sentence

const sentence4 = "you are not the intended recipient.";
console.log(normalizeTargetWord(sentence4, "Intended"));
// Output: "you are not the intended recipient." (converts to lowercase)

Support for Accented Characters

This works seamlessly with characters like ñ, ä, é, etc., because JavaScript's native toUpperCase() and toLowerCase() handle Unicode characters correctly:

const accentedSentence = "Él no es el destinatario ñoño.";
console.log(normalizeTargetWord(accentedSentence.toUpperCase(), "ñoño"));
// Output: "ÉL NO ES EL DESTINATARIO ÑOÑO."

Key Features

  • No jQuery or external dependencies: Pure vanilla JavaScript
  • Context-aware: Automatically adapts to the sentence's case style
  • Unicode support: Works with accented and special characters
  • Flexible: Handles all common case scenarios (all upper, all lower, title case, mixed dominant)

内容的提问来源于stack exchange,提问作者William

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:15:50