Link to home
Start Free TrialLog in
Avatar of Wayne Barron
Wayne BarronFlag for United States of America

asked on

JavaScript character count without counting spaces in Textarea (Code provided)

Hello All;

I am currently using the following code, to count the characters in a Textarea.

<script>
 function textChar(val) {
        var len = val.value.length;
        if (len >= 2000) {
        } 
          $('#textNum').text(2000 - len);
      };
</script>

<textarea name="my_textarea" id="my_textarea" placeholder="Enter information here" rows="8" cols="60" onKeyUp="textChar(this);" tabindex="2"></textarea>

Open in new window


The above code works great, love using it.
However, it counts the white spaces as well.
this               and                that
Instead of this being 11 characters, it is 42 characters of which are including the spaces.

I have been searching around and found some scripts that would, but cannot get them to work with what I already have.
(OR) to work with a single field.

I found that I need to do something like this.

replace(/\s+/g,'');

Open in new window


But I am unsure are where to place it at, within my code, to make it work.

Any assistance on this would be great.
Carrzkiss
SOLUTION
Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Wayne Barron

ASKER

I chose Michel's solution, as I am looking for multiple spaces.
Leonidas, thanks for your answer as well.

I am going to use this across the entire site, and get rid of the existing script I was using.
Thank you, both.

Wayne