Finding line breaks in a selection using Javascript?

Sorry, please amateurish from the following, it comes from a designer trying to enter a code: D

What I'm trying to achieve here is to return the number of highlighted / highlighted lines with the cursor. Under “lines,” I refer to what the user sees, not the line of HTML code (what he is doing at the moment). Also, "line break", I do not mean the HTML tag, but typographic break or "soft return".

So, I'm stuck on now selection.split("\n"), which, of course, is broken down only into "new lines." Is there a way to split the selected line into line breaks?

Hope this all makes sense!

function measure() {
  var str = window.getSelection();
  var selection = str.toString();
  var arr = selection.split("\n");
  if (arr != ""){
    document.getElementById('length').innerHTML = arr.length;
  }
  else {
    document.getElementById('length').innerHTML = "0";
  }
};

document.addEventListener('mouseup', measure, false);
body {
  width: 80%;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
<p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p><em>Selected lines:</em> <span id="length">0</span></p>
Run code
+4
1

, . , , , . :

function measure() {
  var str = window.getSelection();

  var range = str.getRangeAt(0);
  var rects = range.getClientRects();
  document.getElementById('length').innerHTML = rects.length;
};

document.addEventListener('mouseup', measure, false);

, , .

, !

0

All Articles