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

求助:JavaScript实现网页span标签内指定单词替换并保留大小写

Fixing Case-Preserving Word Replacement in JavaScript Spans

Hey there! Let's sort out this replacement issue for you. The problem with your current code is twofold: first, you're hardcoding a loop to run 100 times (which will throw errors if there are fewer than 100 <span> elements), and more importantly, you're replacing the entire inner content of each span with a lowercase "smurf" instead of targeting just the word "katt" while preserving its original capitalization.

Here's a better approach that uses a regular expression with a callback function to handle different capitalization scenarios—this aligns with what you mentioned about needing conditional logic (the callback acts like your if/else checks):

// Get all span elements on the page
const allSpans = document.getElementsByTagName("span");

// Loop through each span
for (const span of allSpans) {
  // Replace "katt" (case-insensitive) while matching original capitalization
  span.innerHTML = span.innerHTML.replace(/katt/gi, (matchedWord) => {
    if (matchedWord === matchedWord.toUpperCase()) {
      // If the matched word is all uppercase, return all-uppercase replacement
      return "SMURF";
    } else if (matchedWord.charAt(0) === matchedWord.charAt(0).toUpperCase()) {
      // If only the first letter is uppercase, return title-case replacement
      return "Smurf";
    } else {
      // Otherwise return lowercase
      return "smurf";
    }
  });
}

Let's break this down:

  • /katt/gi: The regex pattern where g means "global" (replace all instances of "katt" in a span, not just the first one) and i means "case-insensitive" (matches "katt", "Katt", "KATT", etc.).
  • The callback function takes the exact matched string (e.g., "Katt" or "KATT") and uses conditional checks to return the correctly capitalized version of "smurf".
  • We loop through the actual collection of spans (using for...of which is cleaner than a traditional for loop) instead of hardcoding a number, so we won't run into errors if there are fewer than 100 spans.

If you prefer to use a traditional for loop (closer to your original code), here's that version:

const allSpans = document.getElementsByTagName("span");

for (let i = 0; i < allSpans.length; i++) {
  const span = allSpans[i];
  span.innerHTML = span.innerHTML.replace(/katt/gi, (matchedWord) => {
    if (matchedWord === matchedWord.toUpperCase()) {
      return "SMURF";
    } else if (matchedWord[0] === matchedWord[0].toUpperCase()) {
      return "Smurf";
    }
    return "smurf";
  });
}

Either version will preserve the original capitalization of "katt" in your spans. Give it a test!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:37:26