Strange behaviour with range.toString()

强颜欢笑 提交于 2019-12-24 17:57:04

问题


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

<div>
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?


回答1:


This should do it:

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



回答2:


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();


来源:https://stackoverflow.com/questions/1586231/strange-behaviour-with-range-tostring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!