JSFiddle - React, Tailwind, and code Playground
HTML
<div class="original">Вдфлоывр щфцшгв рфышщв гнфщц вгфшцв нтфщшц твнфщц шгвнфт цщвшг нфтцщвш гфцнтщ вшгфц нтвщфшгц еташщфцг анифцшн еафгцша нфепц шлфгнцат лщфнцат гфлцнап тлфгцан </div>
<div class="extracted-lines"></div>
SCSS
$chartColors: #56c7fa, #f76540, #ffcb05, #62cd9f, #b67baa;
@for $i from 1 through length($chartColors) {
$chartColors: append($chartColors, invert(nth($chartColors, $i)));
}
$chartColorsLength: length($chartColors);
* {
margin: 0;
padding: 0;
}
body {
display: flex;
}
body > div {
width: 50%;
}
.original {
border: 1px solid salmon;
}
.extracted-lines {
border: 1px solid lime;
color: white;
@for $i from 1 through $chartColorsLength {
:nth-of-type(#{$chartColorsLength}n+#{$i}) {
background-color: nth($chartColors, $i);
}
}
}
JavaScript
HTMLElement.prototype.forEachTextLine = function(callback) {
if (!this.hasOwnProperty('zeroWidthElems')) {
this.words = this.firstChild.nodeValue.trim().split(/\s+/);
this.removeChild(this.firstChild);
this.zeroWidthElems = new Array();
var newTextNode;
for (var i = 0; i < this.words.length; i++) {
newTextNode = document.createTextNode((i ? ' ' : '') + this.words[i]);
this.appendChild(newTextNode);
this.zeroWidthElems.push(document.createElement('span'));
this.zeroWidthElems[i].className = 'zeroWidth';
this.appendChild(this.zeroWidthElems[i]);
}
}
var lineCount = 0, lineText = '';
var maxTop = this.zeroWidthElems[0].offsetTop, curTop = 0;
for (var i = 0; i < this.zeroWidthElems.length; i++) {
curTop = this.zeroWidthElems[i].offsetTop;
if (curTop != maxTop) {
maxTop = curTop;
lineCount++;
callback.call(this, lineCount, lineText, this.zeroWidthElems[i - 1]);
if (i == this.zeroWidthElems.length - 1) {
callback.call(this, ++lineCount, this.words[i], this.zeroWidthElems[i]);
}
lineText = this.words[i];
} else if (i == this.zeroWidthElems.length - 1) {
lineCount++;
lineText += ' ' + this.words[i];
callback.call(this, lineCount, lineText, this.zeroWidthElems[i]);
} else {
lineText += (lineText.length ? ' ' : '') + this.words[i];
}
}
return this;
}
var processEndOfLine = function(line_number, line_text, last_zero_width_element) {
$result.append($('<div>' + line_text + '</div>'));
};
var original = document.querySelector('.original'),
$result = $( document.querySelector('.extracted-lines') );
original.forEachTextLine(processEndOfLine);
$(window).on('resize', function() {
$result.empty();
original.forEachTextLine(processEndOfLine);
});