Anna Laura Davenport Anna Laura Davenport - 4 months ago 16
AngularJS Question

Angular Text Area Counter Line Breaks SMS

I'm trying to make a character counter that mimics a phone for SMS. I've got it counting characters, spaces, and line breaks, however my counters differ. With line breaks, it decrements by 1 in the count for message.length, but does for more than one in the maxlength. I'm thinking that more spaces are added in when indented, but not sure how to get the message.length set the same as maxlength.

<div class="col-md-6">
<textarea rows="4" class="form-control" data-ng-model="message" maxlength="160" data-ng-trim="false"></textarea>
<h6 id="characters">
<span>Characters left: {{160 - message.length}}</span>

Also- this answer doesn't actually work for this (it counts spaces and line breaks as 1):
angularjs text area character counter


So the only thing you need to count as two characters are actual line breaks (line breaks entered manually by the user, not “virtual” line breaks caused by the text being longer than the textarea width allows)?

Then I’d suggest this:

<span>{{160 - message.length - (message.length ? message.split("\n").length-1 : 0)}} left</span>

<script src=""></script>

<body ng-app>
  <textarea ng-model="message" ng-trim="false" maxlength="160"></textarea>
  <span>{{160 - message.length - (message.length ? message.split("\n").length-1 : 0)}} left</span>

message.split("\n").length counts the number of parts you get after you split the message at line breaks. A message without a line break gets you one “part”, a message with one line break gets you two parts, etc. – hence the -1. And splitting an empty string still gets you one result, therefor the check if the message has a length at all first.

By definition, a browser has to return line breaks in a textarea’s value as \n – those are counted as one character by message.length already, so we just subtract the number of \n characters again, thereby counting each \n as two characters in the result. (I suppose they are counted as two in an SMS text message length, because that might actually be using \r\n for line breaks.)