After searching almost all question related on how to delete the text between character such as @ and carret position in contenteditable div, Am almost in conclusion that this question has become impossible to community. See the following question and non of them actually solved the deleting task. Contenteditable div get and delete word preceding caret, How to get range of characters between @ and caret in contenteditable, Remove last x characters before carret position, return the range object of the word before or upon carret position in contenteditable div
Am also stuck. What we are looking for is
- Create a content editable div and a button value="playing".
- Type anything in contenteditable div and begin with any character eg @
- Example Assuming | symbol represent the carret in a sentence "I am @sch|ool with friends",
- since the carret is upon the word school, replace the word @school with playing. Remember @ symbol will no longer exist too.
- If possible, set the carret after the word playing.
- Final expected result is sentence "I am playing with friends".
Some of us are not familiar with range and selection and we are hereby requesting for help. Meanwhile, let me try a creating a fiddle. Thanks
function replace_with_playing(){
var sel='';
if(window.getSelection){//webkits plus firefox
var sel=document.getSelection();
sel.modify("extend","backword","word");
range=sel.getRangeAt( 0);
range.deleteContents();
var el=document.createElement('span');
el.innerHTML='Playing';
$(el).attr('contenteditable','false');
var frag=document.createDocumentFragment(),node;
while(node=el.firstChild){
frag.appendChild(node);
}
range.insertNode(frag);
range.collapse();
//this code is appending the word playing but not deleting the word @school
}
else if(document.selection){//IE
//i dont know code for IE
}
}
$(document).on('click','.bt',function(){
var el=document.getElementById('editable_div');
replace_with_playing();
});
.parent_container{
position:relative;
}
.editable_div{
width:200px;
padding:5px 10px;
min-height:50px;
border: 1px #DCDCDC solid;
}
.bt{
width:70px;
border:1px #000 solid;
position:absolute;
left:100px;
bottom:-30px;
background:#ffff00;
padding:2px 8px;
}
.description{
margin-top:10px;
}
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<div class="parent_container">
<button class="bt">playing</button>
<div class="editable_div"id="editable_div"contenteditable>
</div>
<div class="description">Type am "@school" such that the carret is after school then click playing</div>
</div>