Javascript to Count Line Breaks [SOLVED]
Posted: Mon May 15, 2006 2:44 pm
Computers are stupid, so when calculating the length of a field using javascript, I apparently need to count line breaks twice.
For example, this string ought to return a length of 10:
I'm using this function:
Only, for some reason, it's not working as intended. It only recognizes the first line break, not subsequent ones. What's the deal?
Any ideas?
For example, this string ought to return a length of 10:
Code: Select all
One
TwoCode: Select all
<script type="text/javascript">
function countMe(obj) [obj = the textarea]
{ // figure out how many characters have been entered
if(!obj) return;
var iLength = obj.value.length; // characters used (including line breaks as one char each)
var aBR = obj.value.match(new RegExp("(\\n)")); // count line breaks
var iBR = aBR ? aBR.length : 0; // if no line breaks found, return 0, else return count
var iUsed = iLength + iBR; // the number of characters used should count line breaks twice
return; // exit
}
</script>Any ideas?