简体   繁体   English

如何计算每一行文字中的符号?

[英]How to count symbols in each line of text?

I have some text in a pre tag with a fixed width and I need to count how many characters in each line of this chunk of text. 我在固定宽度的pre标签中有一些文本,我需要计算这块文本的每一行中有多少个字符。 For example, in the sample below first line has 80 characters, 2nd has 79, 3rd - 81 and so on. 例如,在下面的示例中,第一行有80个字符,第二行有79个字符,第三行-81等。 When we have an empty string with a newline it should be just 1. 当我们有一个带有换行符的空字符串时,它应该仅为1。

 pre { display: block; white-space: pre-wrap; background: white; border-color: white; word-break: normal; width: 600px; } 
 <pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit, nisl eget dapibus condimentum, ipsum felis condimentum nisi, eget luctus est tortor vitae nunc. Nam ornare dictum augue, non bibendum sapien pulvinar ut. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras congue congue purus, quis imperdiet tellus ornare in. Nulla facilisi. Nulla elementum posuere odio ut ultricies. Nullam tempus tincidunt elit eget posuere. Pellentesque sit amet tellus sapien. Praesent sed iaculis turpis. Nam quis nibh diam, sed mattis orci. Nullam ornare adipiscing congue. In est orci, consectetur in feugiat non, consequat vitae dui. Mauris varius dui a dolor convallis iaculis.</pre> 

Is this even possible to do? 这有可能吗?

Folowing the approach found at How can I count text lines inside an DOM element? 遵循“ 如何计算DOM元素内的文本行”中找到的方法 Can I? 我可以吗? I finally managed to achieve the code below. 我终于设法实现了以下代码。 The tricky part is that the line-height must be given with css, so we can calculate the number of lines. 棘手的是,行高必须使用css来指定,因此我们可以计算行数。

[update] [更新]

Code updated so that it works at firefox 代码已更新,因此可以在Firefox中使用

<html>
    <head>
        <style>
            pre {
                display: block;
                white-space: pre-wrap;
                background: white;
                border-color: white;
                word-break: normal;
                width: 600px;
                line-height: 1.14em; /* must be defined to work */
            }
        </style>
    </head>
    <body>
        <pre id="preContent">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit, nisl eget dapibus condimentum, ipsum felis condimentum nisi, eget luctus est tortor vitae nunc. Nam ornare dictum augue, non bibendum sapien pulvinar ut. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras congue congue purus, quis imperdiet tellus ornare in. Nulla facilisi. Nulla elementum posuere odio ut ultricies. Nullam tempus tincidunt elit eget posuere. Pellentesque sit amet tellus sapien. Praesent sed iaculis turpis. Nam quis nibh diam, sed mattis orci. Nullam ornare adipiscing congue. In est orci, consectetur in feugiat non, consequat vitae dui. Mauris varius dui a dolor convallis iaculis.</pre>
        <script>
            function calcLineChars(elem){
                var cpy = elem.innerHTML;
                var totalLines = countLines(elem);
                elem.innerHTML = '';
                var result = [];
                var charCounter = 0;
                var lastCount = 0;
                for(var i = 0; i < totalLines; i++){
                    console.log(i);
                    elem.innerHTML += cpy[charCounter];
                    while((i + 1) == countLines(elem) && charCounter < cpy.length - 1){
                        charCounter ++;
                        elem.innerHTML += cpy[charCounter];
                    }
                    charCounter ++;
                    var currentLength;
                    if((i + 1) != countLines(elem)){
                        currentLength = elem.innerHTML.substring(0, elem.innerHTML.lastIndexOf(' ')).length + 1;
                    }else{
                        currentLength = elem.innerHTML.length;
                    }
                    result.push(currentLength - lastCount);
                    lastCount = currentLength;
                }
                return result;
            }

            function countLines(elem) {
                var elemHeight = elem.offsetHeight;
                var lineHeight = elem.style.lineHeight || document.defaultView.getComputedStyle(elem, null).getPropertyValue("line-height");
                if(lineHeight.indexOf('px') != -1){
                    lineHeight = lineHeight.substring(0, lineHeight.length - 2);
                }
                lineHeight = parseFloat(lineHeight);
                var lines = elemHeight / lineHeight;
                var intLines = parseInt(lines);
                if(lines - intLines >= 0.1){
                    intLines ++;
                }
                return intLines;
            }

            var lineChars = calcLineChars(document.getElementById('preContent'));
            var message = '';
            for(var i = 0, current; current = lineChars[i]; i++){
                message += '\n' + 'line ' + (i + 1) + ' has ' + current + ' chars';
            }
            alert(message);
        </script>
    </body>
</html>

You loop through the text and count until you found a line break element. 您遍历文本并计数直到找到换行元素。 When you encounter a newLine character push count to array and start count from zero for new line 当遇到newLine字符时,将计数推入数组并从零开始为新行计数

   input= document.getElementById("countDiv").innerHTML();
    var length = input.length;
    var lines=[]//number lines 
    var count=0;//counting character at each line
    for ( var i = 0; i < length; i ++ )
    {
    if (input.charAt(i)=='\n')
    {
    lines.push(count);
    count=0;
    }
    else{
    count=count+1;
    }

    }

Hello this is what I came up with. 您好,这是我想出的。

//html
<pre id="countDiv">monkeyman</pre>
//JS
var x = document.getElementById("countDiv");
var y = x.innerHTML;
console.log(y.length);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM