Take the 2-minute tour ×

How can I count the number of spaces of the current line in a textarea


If my cursor is current on line 2 then the result should be: 3

share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

Here is the code:

window.onload = function () {
    var ta = document.getElementById('ta'); //set your textarea's id
    ta.onclick = function (e) {
        var lineNo = ta.value.substr(0, ta.selectionStart).split(/\r?\n|\r/).length,
            lineText = ta.value.split(/\r?\n|\r/)[lineNo - 1],
            numOfSpaces = lineText.split(/\s/).length - 1;
        console.log(lineNo, lineText, numOfSpaces);

Here is the fiddle.

NOTE: textarea.selectionStart does not work in some browsers. For a cross-browser support see this post.

share|improve this answer
add comment

You need to split the string value of the textarea and then:

var textString = //pull data from textarea
var textArray = textString.split("\n");
for(var i=0; i<textArray.length; i++) {
    var count = textArray[i].match(/ /g); //regex to get any number of spaces 


share|improve this answer
If the regular expression includes the g flag, the method returns an Array containing all matches. –  Samuel Liew Feb 19 '13 at 1:58
Why not be constructive instead of down voting? –  jimjimmy1995 Feb 19 '13 at 2:01
OP needs more granular solution , wants to know based on cursor posiiton. ALso your loop is checking the same textArray[0] each time –  charlietfl Feb 19 '13 at 2:03
You'll need to get cursor position and then do the loop: stackoverflow.com/questions/1891444/… –  Ray Cheng Feb 19 '13 at 2:10
@RayCheng Exactly. I am just showing that you can get data for each line. You would find the cursor line and pass that into var count = textArray[i].match(/ /g); instead of looping. –  jimjimmy1995 Feb 19 '13 at 2:21
show 4 more comments

Your Answer


