return the range object of the word before or upon

2019-08-19 09:07发布

问题:

After research, i came accross few answers by @Tim Down but still did not quench my thirst. What i want is to delete the contents of range containing the word before or upon carret in contenteditable div. Assuming | represent carret position.

Example: @TimDown is a #GoodJavascriptProgrammer| and ....

if i click a delete button, i should delete word #GoodJavascriptProgrammer with # symbol included and set cursor back to its position. see my fiddle delete last string before carret

function delete_last_word_at_carret(el){
if(window.getSelection){//Webkits and Firefox code
    var sel=document.getSelection();
if(sel.getRangeAt && sel.rangeCount){
        range=sel.getRangeAt(0);//assume this is required range
        range.deleteContents();
  //the word #GoodJavascriptProgrammer should be deleted
  //and cursor set back to the right position
   set_cursor();
    }
 }
 else if(document.selection){//IE code
 //help with code here
 }
}
function set_cursor(){
//return cursor
}
//click the delete button
$('.delete_bt').click(function(){
var el=document.getElementById('editable_div');
delete_last_word_at_carret(el);
});