Javascript to Count Line Breaks [SOLVED]

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
tomprogers
Forum Commoner
Posts: 50
Joined: Fri Mar 17, 2006 5:17 pm
Location: Minnesota
Contact:

Javascript to Count Line Breaks [SOLVED]

Post 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?
tomprogers
Forum Commoner
Posts: 50
Joined: Fri Mar 17, 2006 5:17 pm
Location: Minnesota
Contact:

Post by tomprogers »

Gah. I needed to use the global flag "g" with my regex.

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

Works now.
Post Reply