Enviado em 13/01/2024 - 23:45h
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
body {
background: #eee;
}
#container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
#result {
width: 80%;
height: 20px;
border: 1px solid #ccc;
padding: 10px;
overflow: auto;
}
.word-quero {
font-weight: bold;
}
.word-brasil {
color: green;
font-weight: bold;
}
</style>
</head>
<body>
<div id="container">
<div id="result" contenteditable></div>
</div>
</body>
<script>
const loadKeyWords = () => {
const keyWords = [];
for (const styleSheet of document.styleSheets) {
for (const cssRule of styleSheet.cssRules) {
if (cssRule.selectorText.includes(".word-")) {
keyWords.push(cssRule.selectorText.split("-")[1]);
}
}
}
return keyWords;
};
const positionCursorInElement = (element) => {
const range = document.createRange();
const select = getSelection();
range.selectNodeContents(element);
range.collapse(false);
select.removeAllRanges();
select.addRange(range);
element.focus();
};
const result = document.querySelector("#result");
const keyWords = loadKeyWords();
result.addEventListener("keyup", () => {
const text = result.innerText;
const regex = new RegExp(`\\s+(${keyWords.join("|")})\\s+`, "gi");
const newText = text.replace(regex, ` <span class="word-$1">$1</span> `);
result.innerHTML = newText;
positionCursorInElement(result);
});
</script>
</html>