开发者

Changing column/row numbers into a character count (JavaScript)

开发者 https://www.devze.com 2023-02-13 03:05 出处:网络
Right now, I have two numbers, a row number and a column number for a textarea.开发者_StackOverflow I need to translate that to the number of characters from the beginning of the textarea.

Right now, I have two numbers, a row number and a column number for a textarea.开发者_StackOverflow I need to translate that to the number of characters from the beginning of the textarea.

Example:

Row 5, character 6 should translate to 108 (The cursor is right after ornare before the period) if I have:

Lorem ipsum dolor sit amet, 
consectetur adipiscing elit. 
Suspendisse scelerisque 
sem in leo venenatis 
ornare. Aenean non
diam eget nisl 
molestie mattis. 

Any ideas how to calculate this via JavaScript?


Here you go:

var area = document.getElementById("txtAreaID");
var rows = area.value.split(/\n/);

var getTotal = function(row, col){
    var tot = 0;
    var i;
    for (i=0; i<(row-1); i++){
        tot+=rows[i].length;
    };
    tot+=col;
    return tot;
};

alert(getTotal(5,6));


var character_count = textarea.value.split(/\n/).slice(0,4).join('').length + 6;
0

精彩评论

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