Javascript 如何删除文本中选定的单词?

Javascript 如何删除文本中选定的单词?,javascript,html,jquery,arrays,if-statement,Javascript,Html,Jquery,Arrays,If Statement,这段代码选择单词并从中生成一个数组。但是我需要在被选中并添加到数组后删除单词。我想我需要使用document.getSelection()或document.selection,但我不知道如何通过它们删除选定的单词。如果有人给我一个暗示,我会很高兴的 <script> let container; var arr = []; function get_selection() { var txt = ''; if (document.getSelection

这段代码选择单词并从中生成一个数组。但是我需要在被选中并添加到数组后删除单词。我想我需要使用document.getSelection()或document.selection,但我不知道如何通过它们删除选定的单词。如果有人给我一个暗示,我会很高兴的

<script>
let container;
var arr = [];
function get_selection() {
  
    var txt = '';
       if (document.getSelection) {
          txt = document.getSelection().toString();
                
                
            } 

            else if (document.selection) {
                txt = document.selection.createRange().text;
            }
             arr.push(txt);
            }
            }
           document.getElementById("txt").onclick = get_selection;

</script>

让容器;
var-arr=[];
函数get_selection(){
var-txt='';
if(document.getSelection){
txt=document.getSelection().toString();
} 
else if(文档选择){
txt=document.selection.createRange().text;
}
arr.push(txt);
}
}
document.getElementById(“txt”).onclick=get\u selection;
您可以使用事件。在元素上或仅在全局上,但您必须确定您的目标不是例如。菜单元素:P。然后您可以使用,如果您在选择之前和之后使用contenteditable和just子字符串值,并将内容值设置为其总和。我使用textarea,在大多数情况下使用contenteditable不是最佳实践

const selections=[]
const handleOnSelect=(e)=>{
const target=e.target;
const start=target.selectionStart;
const end=target.selectionEnd;
const selection=target.value.substring(开始、结束);
选择。推送(选择);
const pre=target.value.substring(0,开始);
const post=target.value.substring(结束);
target.value=前期+后期;
console.log(选项)
}
window.addEventListener(“加载”,()=>{
const target=document.getElementById(“txt”)
target.addEventListener(“选择”,handleOnSelect);
})

这些单词/文本是否在文本区?可以是文本区,但我使用的是div contenteditable。@如果您将我的答案标记为最佳答案,NikN会很高兴:)