मैंने यह पता लगाने की कोशिश की है कि क्या 'getSelection'.anchorNode.parentNode में वर्ग bg-red है, और इसे प्रतिस्थापित करें, लेकिन बहुत सारे दुष्प्रभाव दिखाई देते हैं।
तो, regexp के साथ समाधान ...
(* 1) - यदि आप सामग्री-संपादन योग्य तत्व के कोड का निरीक्षण करते हैं, तो आप देखेंगे कि यह संरचना है: प्रत्येक नई पंक्ति एक अलग div है। \nबहु-पंक्ति चयन की अनुमति देने के लिए, आपको प्रत्येक नई-पंक्ति के प्रतीक को "लाइन-ब्रेकिंग" HTML से बदलना होगा ।
(* 2) - ब्राउज़र सम्मिलित करता है कि यह HTML का अपना सुधार है और सही प्रतिस्थापन को रोकता है। मुझे किसी भी गैर-HTML स्ट्रिंग को सम्मिलित करने के लिए मजबूर किया गया था, जो पाठ में दिखाई देने की संभावना नहीं है। और सभी प्रतिस्थापन के बाद - वैध HTML डालें।
(* 3) - मैं यहाँ सभी नियमित अभिव्यक्तियों का विश्लेषण करने की सलाह देता हूँ → https://regex101.com/r/j88wc0/1 मुख्य विचार यह है कि सभी दोहरे दिखावे को प्रतिस्थापित किया जाए <span class="bg-red"> anything instead of closing span <span class="bg-red">या </span> anything instead of starting span tag </span>।
ध्यान दें, कि यह कोड सभी आंतरिक HTML को ताज़ा करता है, हर बार जब आप बटन दबाते हैं। यह कुछ हजार लाइनों से पाठ के साथ भी काम नहीं करेगा)
let button = document.getElementById("button");
let block = document.getElementById("block");
button.addEventListener('click', function(){
let s = window.getSelection();
let str = s.toString().replace(/\n/g,'</span></div><div><span class="bg-red">'); // (*1)
document.execCommand("insertHTML", false, `bubufication`); // (*2)
block.innerHTML = block.innerHTML
.replace(/bubufication/, `<span class="bg-red">${str}</span>`)
.replace(/<span class="bg-red">(.*?)<\/span><span class="bg-red">/g,'$1<span class="bg-red">')
.replace(/<span class="bg-red">(((?!<\/span>).)*?<span class="bg-red">)/g,"$1")
.replace(/(<\/span>((?!<span class="bg-red">).)*)<\/span>/g,"$1"); // (*3)
});
.bg-red {
background-color: red;
}
<div id="block" contenteditable="true">
<div>this is testing this is testing this is testing</div>
<div>this is testing this is testing this is testing</div>
</div>
<button id="button">mark</button>