I'm using Rangy 1.2. Let's say the user selects the text " abcd". I am trying to trim the selection to just be "abcd".
I have already created a Rangy selection, and range on the selection. It seems like the function I want to use is setStartAfter(node) but it isn't returning anything for me.
I have been following these docs: https://code.google.com/p/rangy/wiki/RangyRange
Thanks
In general, this is a little tricky because the space character may not be part of the same node as "abcd". Rangy 1.2 doesn't have any special methods to help you: the Range implementation is just the same as DOM Range, with a few extensions, so the problem is no different to what it would be without Rangy. If all of the text is within a single text node, say "123 abcd efg", and the user had selected " abcd", you'd need to do something like this, assuming you have a reference to the text node in a variable called textNode
and the selection range in a variable called range
:
range.setStart(textNode, 4);
rangy.getSelection().setSingleRange(range);
Rangy 1.3, however, has a TextRange module to deal with ranges and selections in terms of their text. With it, your problem could be solved with
rangy.getSelection().trim();
Demo:
<script src="https://rawgit.com/timdown/rangy-release/master/rangy-core.js"></script>
<script src="https://rawgit.com/timdown/rangy-release/master/rangy-textrange.js"></script>
<input type="button" onmousedown="rangy.getSelection().trim(); return false" value="Trim selection">
<div contentEditable="true">
Please select something in here and press the button abcd efgh
</div>