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
您需要拆分 textarea 的字符串值,然后:
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);
}
这是代码:
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);
}
}
这是小提琴。
注意:在某些浏览器中不起作用。如需跨浏览器支持,请参阅这篇文章。 textarea.selectionStart