Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count chars without spaces with AngularJs

I need to count chars of a text with and with out spaces.

This is my attemp, but count the text without only the first space.

<div style="max-width:80%; margin: 10px auto">
<section class="row" ng-app="">
    <div class="col-lg-8">
        <div class="panel panel-default">
            <div class="panel-heading">Paste your text for <b>words count</b></div>
            <div class="panel-body">
                <textarea class="form-control" rows="10" ng-model="wordcounter"></textarea>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="panel panel-default">
            <div class="panel-heading">Words and characters</div>
            <ul class="list-group">
                <li class="list-group-item">Characters (with space)<span class="badge">{{wordcounter.length}}</span></li>
                <li class="list-group-item">Characters (no space)<span class="badge">{{wordcounter.replace(" ","").length}}</span></li>
            </ul>
        </div>

    </div>
</section>

https://jsfiddle.net/a4Lahp6v/

like image 541
WalterV Avatar asked Sep 27 '26 00:09

WalterV


1 Answers

You only replace one space

Without regex

The problem is that currently, you are only replacing one space instead of all the spaces in the string. One way you can solve this is by splitting the string by all spaces that are in the string str.split(" "); and then joining them together. (glueing the words together again without the space) with join.

Change your binding for the counter without spaces like this {{wordcounter.split(" ").join("").length}}

 <div style="max-width:80%; margin: 10px auto">
    <section class="row" ng-app="">
<div class="col-lg-8">
    <div class="panel panel-default">
        <div class="panel-heading">Paste your text for <b>words count</b></div>
        <div class="panel-body">
            <textarea class="form-control" rows="10" ng-model="wordcounter"></textarea>
        </div>
    </div>
</div>
<div class="col-lg-4">
    <div class="panel panel-default">
        <div class="panel-heading">Words and characters</div>
        <ul class="list-group">
            <li class="list-group-item">Characters (with space)<span class="badge">{{wordcounter.length}}</span></li>
            <li class="list-group-item">Characters (no space)<span class="badge">{{wordcounter.split(" ").join("").length}}</span></li>
        </ul>
    </div>

</div>

like image 84
Dylan Meeus Avatar answered Sep 29 '26 12:09

Dylan Meeus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!