I have this
<div id="remove"></div>
<div CONTENTEDITABLE="true"></div>
If a user highlights text in the contenteditable div and clicks on the remove div, I would like to remove that text.
Accepted Answer does not work if one character gets highlighted from left to right.
I used this to remove text:
$("#remove").on('click', function (){
if (window.getSelection().toString() != "") {
selectedText = window.getSelection().toString()
var text1 = $(".selected").text().split("")
pointStart = window.getSelection().anchorOffset
pointEnd = window.getSelection().focusOffset
if (pointEnd < pointStart) {
pointStart = pointEnd
}
text1.splice(pointStart, selectedText.length);
text1 = text1.join("")
} else {
selectedText = $(".selected").text()
var text1 = ""
}
$(".selected").text(text1)
});
With a remove-button instead of a remove-div:
function removeSelectedText () {
if (window.getSelection || document.getSelection) {
var oSelection = (window.getSelection ? window : document).getSelection();
$('#text').text(
$('#text').text().substr(0, oSelection.anchorOffset)
+ $('#text').text().substr(oSelection.focusOffset)
);
} else {
document.selection.clear();
}
}
$('#remove').click(function() {
removeSelectedText();
});
Also see this example.
Adding some content to your HTML:
<div id="remove"><a href="#">Remove</a></div>
<div CONTENTEDITABLE="true">Hello World! This is a test text.</div>
Here's the code:
var getSelected = function(){
var t = '';
if(window.getSelection){
t = window.getSelection();
}else if(document.getSelection){
t = document.getSelection();
}else if(document.selection){
t = document.selection.createRange().text;
}
return t;
};
$('div#remove').click(function(){
var selection = getSelected();
var text = $('div[CONTENTEDITABLE=true]').text();
text = text.replace(selection, '');
$('div[CONTENTEDITABLE=true]').text(text);
});
make div#remove to button#remove
function getSelectedText() {
return window.getSelection ? window.getSelection() // ie9 or above
: document.selection.createRange().text; // earliar ie9
}
$('#remove').click(function() {
var curText = $('#editable').text(),
selObj = getSelectedText(),
selText = selObj.toString();
var newTxt = '';
for (var i = 0; i < curText.length; i++) {
if (i < selObj.anchorOffset || i >= (selObj.anchorOffset + selText.length)) {
newTxt += curText[i];
}
}
$('#editable').text(newTxt);
});