0

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

asdf
   asdf
asdf

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

James
  • 2,811
  • 3
  • 25
  • 29

2 Answers2

0

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 
    alert(count.length);
}

http://jsfiddle.net/2qfHn/

James Coyle
  • 9,922
  • 1
  • 40
  • 48
  • Why not be constructive instead of down voting? – James Coyle Feb 19 '13 at 02:01
  • 1
    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 02:03
  • You'll need to get cursor position and then do the loop: http://stackoverflow.com/questions/1891444/how-can-i-get-cursor-position-in-a-textarea – Ray Cheng Feb 19 '13 at 02: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. – James Coyle Feb 19 '13 at 02:21
  • @charlietfl Fixed the typo as you posted that. :P – James Coyle Feb 19 '13 at 02:24
  • @jimjimmy1995, but that's only half of the story. He still need to find the location of the cursor. This one works better: http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea – Ray Cheng Feb 19 '13 at 02:25
  • @RayCheng Possibly more relevant: http://stackoverflow.com/questions/3153995/find-value-of-current-line-of-a-textarea-using-javascript – James Coyle Feb 19 '13 at 02:31
0

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.

Community
  • 1
  • 1
Onur Yıldırım
  • 32,327
  • 12
  • 84
  • 98