Page 1 of 1

Javascript to Count Line Breaks [SOLVED]

Posted: Mon May 15, 2006 2:44 pm
by tomprogers
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:

Code: Select all

One

Two
I'm using this function:

Code: 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>
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?

Posted: Mon May 15, 2006 2:47 pm
by tomprogers
Gah. I needed to use the global flag "g" with my regex.

RegExp("(\\n)", "g")

Works now.