开发者

javascript textarea lines count

开发者 https://www.devze.com 2023-03-13 14:13 出处:网络
I need to count all lines in textarea. My code: function textareaCurLineNum(obj) { return obj.value.split(/[\\r\\n]/g).length;

I need to count all lines in textarea. My code:

function textareaCurLineNum(obj)
{
    return obj.value.split(/[\r\n]/g).length;
}

In Firefox and Chrome it works good. In Opera it returns for one more.

I try this:

function textareaCurLineNum(obj)
{
    if (!/Opera/.test(navigator.userAgent)){
        return obj.value.split(/[\r\n]/g).length;
    } else {
        return obj.value.split(/[\r\n]/g).length-1;
    }
}

Now, if lines = 3,开发者_运维知识库 opera return 4, 4 lines - 6, 5 lines - 8. Where is a problem?


Square brackets contains set of symbols, not a sequence. split by \n in regexp.

function textareaCurLineNum(obj)
{
    if (!/Opera/.test(navigator.userAgent)){
        return obj.value.split(/\n/g).length;
    } else {
        return obj.value.split(/\n/g).length-1;
    }
}


Try splitting on \n only. The way you wrote it - if I have:

first line \r\n
second line

this split will return 3, since it counts the nothingness between the \r and \n as a line.

A more robust solution will be to first normalise the text by replacing all \r\n (win) and just \r (mac) with \n and then splitting on \n.

0

精彩评论

暂无评论...
验证码 换一张
取 消