To achieve this effect, enclose the specific part of the string you want to highlight with a tag.
input = document.getElementById("input")
result = document.getElementById("result")
input.onkeyup = () => {
// Determine if the ~ is indicating the start or end of the highlighted section
isFramed = false
// Store the resulting HTML in this variable to avoid browser autoclosing error
resultContent = ""
for (let cara of input.value) {
// Check if the current character is a ~
if (cara === '~') {
// and see if it belongs to an existing frame
if (isFramed) {
// Close the frame
resultContent += "</span>"
} else {
// Open a new frame
resultContent += "<span style=\"border: 1px solid black\">"
}
// Toggle isFramed value
isFramed = !isFramed
} else {
// Copy all other characters as they are
resultContent += cara;
}
}
// Set the innerHTML of the result element to the generated string
result.innerHTML = resultContent
}
<input id="input"/>
<div id="result"></div>
Note: To optimize the resulting HTML size, move the styling of <span>
to a separate CSS file.