简体   繁体   English

在 HTML/富文本输入区域中查找和替换选定的文本

[英]find and replace selected text within an HTML/rich text input area

I have a rich text editor (nicEditor) that stores input in a markup like so:我有一个富文本编辑器(nicEditor),它将输入存储在标记中,如下所示:

<div
    style="
        color: #bababa;
        background-color: #0c0a08;
        font-family: Menlo, Monaco, 'Courier New', monospace;
        font-weight: normal;
        font-size: 15px;
        line-height: 23px;
        white-space: pre;
    "
>
    <div>
        <span style="color: #bababa"> selectionRange</span
        ><span style="color: #9d8262">.</span
        ><span style="color: #bababa">range</span
        ><span style="color: #9d8262">.</span
        ><span style="color: #bababa">endContainer</span
        ><span style="color: #9d8262">.</span
        ><span style="color: #bababa">innerHTML</span
        ><span style="color: #9d8262"> =</span
        ><span style="color: #bababa"> newParent</span
        ><span style="color: #9d8262">.</span
        ><span style="color: #bababa">innerHTML;</span>
    </div>
</div>

the above is the state i can access, but the actual content rendered is as follows:以上是我可以访问的state,但实际渲染的内容如下:

selectionRange.range.endContainer.innerHTML = newParent.innerHTML;

i want to be able to select something in the rendered text (say, the second occurance of innerHTML ) and replace it with something else, what could be the optimal way of achieving this (without using jQuery)?我希望能够 select 呈现文本中的某些内容(例如,第二次出现innerHTML )并将其替换为其他内容,实现此目的的最佳方法是什么(不使用 jQuery)? the key idea is replacing a selection and not just the first occurance of the input .关键思想是替换选择,而不仅仅是输入的第一次出现

 foo=function() { var selection= window.getSelection().getRangeAt(0); var selectedText = selection.extractContents(); var span= document.createElement("span"); span.innerHTML = `{{C1::${selectedText.textContent}}}` selection.deleteContents(); selection.insertNode(span); }
 <div style=" color: #bababa; background-color: #0c0a08; font-family: Menlo, Monaco, 'Courier New', monospace; font-weight: normal; font-size: 15px; line-height: 23px; white-space: pre; " > <div> <span style="color: #bababa"> selectionRange</span ><span style="color: #9d8262">.</span ><span style="color: #bababa">range</span ><span style="color: #9d8262">.</span ><span style="color: #bababa">endContainer</span ><span style="color: #9d8262">.</span ><span style="color: #bababa">innerHTML</span ><span style="color: #9d8262"> =</span ><span style="color: #bababa"> newParent</span ><span style="color: #9d8262">.</span ><span style="color: #bababa">innerHTML;</span> </div> </div> <input type="button" onclick="foo();" value="FOO"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM