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
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
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);
}
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.