开发者

Strange behaviour with range.toString()

I want to get back the text that I select in an element using the Range object provided by Mozilla's flavour of javascript.

So I do this:

//assume that I'm only using Firefox, and there is just one selection
var range = window.getSelection().getRangeAt(0);
var rangeText = range.toString();

This works OK when the html of the selected text doesn't have any newlines In other words, if I have the following html:

<div>One. Two. Three. Four. Five.</div>

and I select Two. Three. Four., then everything is fine.

On the other hand, if I have

<开发者_StackOverflowdiv>
One.
Two.
Three.
Four.
Five.
</div>

and I select Two. Three. Four. as before, there are newlines introduced into the result returned from Range.toString(); the newlines are after Two., Three., and Four.

Obviously, when displayed in the browser, both html fragments are identical. Is there a way I can ensure that the same text is returned without newlines?


This should do it:

range.toString().replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '')


OK, I used part of the answer from Tim Down in the end:

  var sel = window.getSelection();
  var range = sel.getRangeAt(0);
  var range2 = range.cloneRange();

  //do some stuff with range2...

  var rangeText, range2Text;

  sel.removeAllRanges();
  sel.addRange(range);
  rangeText = sel.toString();

  sel.removeAllRanges();
  sel.addRange(range2);
  range2Text = sel.toString();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜