JSFiddle - React, Tailwind, and code Playground
HTML
<div id="text" contenteditable="true"></ div>
CSS
.green {
color: green;
}
#text {
border: 1px solid rgba(0, 0, 0, .2);
}
JavaScript
var text = document.getElementById('text');
var closingTag = "</b>";
text.onkeyup = function(evt) {
// replace the string
this.innerHTML = this.textContent.replace(/Brasil/ig, '<b class="green">Brasil</b>');
// add an empty text node to the contenteditable element
// so that we can move the cursor to it
this.appendChild(document.createTextNode(""));
// moving the cursor at the end of the element
setCaret();
};
function setCaret() {
var el = document.getElementById("text");
var range = document.createRange();
var sel = window.getSelection();
// get the last child node from the contenteditable element
// it's an empty node, so set the offset to 0
range.setStart(el.childNodes[el.childNodes.length - 1], 0);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
el.focus();
}