求助:JavaScript实现网页span标签内指定单词替换并保留大小写
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 wheregmeans "global" (replace all instances of "katt" in a span, not just the first one) andimeans "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...ofwhich 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

