How to break an HTML paragraph into its lines of text using JavaScript

Is it possible (and how can I) to split a paragraph of text into relevant lines using JavaScript. What I would like to do is implement the hanging punctuation on each line of a paragraph or blockquote, and not just on the start line.

Any other ideas are also welcome!

Clarification . I was asked to be less ambiguous as to what “splitting a paragraph into appropriate lines” means.

In HTML, an element <p>creates a block of text. Similarly, many other elements. These text bodies are wrapped according to the width (regardless of whether the css width is set or assumed by default). I cannot find where line breaks occur using regex or any other means. So, let the paragraph end with a length of 7 lines, I would like to discover that these are seven lines, and where these lines begin and end.

Searching \nor \r, it seems, gives nothing.

+4
source share
2 answers

, span. offsetTop , , .

getLines() , span . , , CSS, , .

//So it runs after the animation
setTimeout(function(){
    splitLines();
    showLines();
}, 1000)

function showLines() {
  var lines = getLines();
  console.log(
    lines.map(function(line) {
      return line.map(function(span) {
        return span.innerText;
      }).join(' ')
    }));
}

function splitLines() {
  var p = document.getElementsByTagName('p')[0];
  p.innerHTML = p.innerText.split(/\s/).map(function(word) {
    return '<span>' + word + '</span>'
  }).join(' ');
}



function getLines() {
  var lines = [];
  var line;
  var p = document.getElementsByTagName('p')[0];
  var words = p.getElementsByTagName('span');
  var lastTop;
  for (var i = 0; i < words.length; i++) {
    var word = words[i];
    if (word.offsetTop != lastTop) {
      lastTop = word.offsetTop;
      line = [];
      lines.push(line);
    }
    line.push(word);
  }
  return lines;
}
<p>Here is a paragraph that we want to track lines for. Here is a paragraph that we want to track lines for. Here is a paragraph that we want to track lines for Here is a paragraph that we want to track lines for Here is a paragraph that we want to track
  lines for Here is a paragraph that we want to track lines for</p>
Hide result

, http://jsfiddle.net/4zs71pcd/1/

+4

, hanging-punctuation css , . , , <p> ( blockquotes) hanging-punctuation: 'first' . hanging-punctuation ().

, (\n) , , . , (- ). , , <p> , . , - , . Heres blogpost, , .

+1

All Articles