<div class="text-container" id="text-container">
<!-- Example passage of text -->
This is a TEST passage. In this passage, we have several ALL-CAPS WORDS such as TEST, HELLO, and WORLD. We also have mixed case words and normal lowercase words. Only the all-caps WORDS should be highlighted.
</div>
/* Define the three classes for cycling colors */
.color1 {
color: red;
}
.color2 {
color: green;
}
.color3 {
color: blue;
}
.text-container {
font-size: 18px;
line-height: 1.5;
margin: 20px;
}
// Call the function when the page loads
document.addEventListener("DOMContentLoaded", () => {
// Function to wrap all-caps words in a span with a cycling class
function highlightAllCaps() {
const container = document.getElementById("text-container");
let text = container.innerHTML;
// Updated Regex pattern to match all-caps words, including hyphenated ones (2 or more letters)
const allCapsPattern = /\b[A-Z]{2,}(?:-[A-Z]{2,})*\b/g;
// Array of class names to cycle through
const classes = ["color1", "color2", "color3"];
let classIndex = 0;
// Replace the all-caps words with the wrapped spans
text = text.replace(allCapsPattern, function (match) {
const span = `<span class="${classes[classIndex]}">${match}</span>`;
classIndex = (classIndex + 1) % classes.length; // Cycle through classes
return span;
});
// Set the updated HTML back to the container
container.innerHTML = text;
}
highlightAllCaps();
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.