Count chars without spaces with AngularJs
我需要计算带空格和不带空格的文本的字符数。
这是我的尝试,但是在没有第一个空格的情况下计算文本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <section class="row" ng-app=""> Paste your text for words count <textarea class="form-control" rows="10" ng-model="wordcounter"></textarea> Words and characters <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> </section> |
https://jsfiddle.net/a4lahp6v/
只替换一个空格没有正则表达式
问题是,当前您只替换了一个空格,而不是字符串中的所有空格。解决这个问题的一种方法是,将字符串拆分为字符串
把你的柜台包扎改成这样,不留空格。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <section class="row" ng-app=""> Paste your text for words count <textarea class="form-control" rows="10" ng-model="wordcounter"></textarea> Words and characters <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> |
你可以使用regex来获取标签等。
wordcounter.replace(/s/g,")
也可以使用角度自定义过滤器来完成此操作。
1 2 3 4 5 6 7 8 9 10 | angular.module("app", ["core"]); angular.module("core", []); angular.module("core").filter('count', function() { return function(input, incSpace) { input = input ||""; return incSpace ? input.length : input.replace(/\s/g, '').length; }; }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <script src="https://code.jquery.com/jquery-3.1.0.min.js"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"> <body ng-app="app"> <section class="row" ng-app=""> Paste your text for words count <textarea class="form-control" rows="10" ng-model="wordcounter"></textarea> Words and characters <ul class="list-group"> <li class="list-group-item">Characters (with space)<span class="badge">{{wordcounter | count:true}}</span> </li> <li class="list-group-item">Characters (no space)<span class="badge">{{wordcounter | count:false}}</span> </li> </ul> </section> </body> |