How can I count how many lines of text a <pre>
tag contains?
I want to append a absolute div with line numbers next to it.
To count number of text lines inside DOM element, we will use the following approach. Obtain the total height of content inside the DOM element. Obtain the height of one line. By dividing the total height of the content by the height of one line, you get the total number of lines inside the element.
To get the number of lines in an element, we can divide the element's height by its line-height. Then we can do the computation by writing: const el = document. querySelector('div'); const divHeight = +el.
To count the number of lines of a string in JavaScript, we can use the string split method. const lines = str. split(/\r\n|\r|\n/);
you could use the javascript split function to count the line breaks.
$('pre').html().split(/\n/).length
better
$('pre').html().match(/\n/)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With