I've got a large piece of text which I want to be able to select, storing the selected part by its startindex and endindex. (For example, selecting or in word would give me startindex 1 and endindex 2.)
This all works properly, but I've got a problem with HTML entities such as & (the ampersand).
I've created a little case in which the issue consists. You can see in the fiddle below that the startIndex inflates if you select anything beyond the &, because it doesn't count the & as a single character, but rather 5 characters: &.
Is there a way to make it count properly special characters like the ampersand, without screwing up the index?
JavaScript
$(document).ready(function() {
$('#textBlock').mouseup(function() {
var selectionRange = window.getSelection();
if (!selectionRange.isCollapsed) {
selectedText = selectionRange.getRangeAt(0).toString();
}
document.getElementById('textBlock').setAttribute('contenteditable', true);
document.execCommand('strikethrough', false);
var startIndex = $('#textBlock').html().indexOf('<strike>');
$('#startindex').html('the startindex is: ' + startIndex);
done();
});
});
function done() {
document.getElementById('textBlock').setAttribute('contenteditable', false);
document.getSelection().removeAllRanges();
removeStrikeFromElement($('#textBlock'));
}
function removeStrikeFromElement (element) {
element.find('strike').each(function() {
jQuery(this).replaceWith(removeStrikeFromElement(jQuery(this)));
});
return element.html();
}
I think/know it has to do with the $('#textBlock').html() used to do the indexOf instead of text(). The best way to get a start and endindex was to <strike> through the selected text since the execCommand let's me do that and it's a HTML tag never used in the application.