I'm trying to remove leading or trailing (sometimes both) whitespace from the user selected text. Implemented according to this answer. This works for simple cases, however, when the selected text contains tags or
, it fails.
Example: in the fiddle try to highlight -- hi this is bob.
from right to left, including the space at the end, then press Trim.
This results in:
Uncaught IndexSizeError: Failed to execute 'setEnd' on 'Range': The offset 24 is larger than or equal to the node's length (5).
I guess this can be caught with
if (method == range.setEnd && range.startOffset + ind >= range.endContainer.length)
but I'm not sure how to handle it. I've also tried to replace the hard spaces using
e2 = document.getElementById('e2');
e2.innerHTML = e2.innerHTML.replace(/ /gi, ' ');
However, this makes the selection empty. Code:
function removeWsFromSelection(fromStart) {
selection = window.getSelection();
range = selection.getRangeAt(0);
if (fromStart) {
regex = /[^\s]/;
container = range.startContainer;
method = range.setStart;
} else {
regex = /\s+$/;
container = range.endContainer;
method = range.setEnd;
}
match = regex.exec(selection.toString());
if (match) {
ind = match.index;
if (ind > 0) {
// ind is the first non-ws char from the start or first ws char from the end,
// hence (startOffset + ind)
method.call(range, container, range.startOffset + ind);
rng = range.cloneRange();
selection.removeAllRanges();
selection.addRange(rng);
}
}
}
BTW, unfortunately, Selection.modify
didn't work for me, and besides it's considered non-standard.