使用angular定义用于截取特定长度的过滤器,并使用自定义符号(包括“...”)在末尾进行替换
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>stringSub</title> </head> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <body ng-app="myApp" ng-controller="myController"> <span style="background: #ddd;border-radius: 4px;padding:2px;">{{arr | cutTxt:55:"..."}}</span> </body> <script> var app = angular.module('myApp', []); app.controller('myController', function($scope) { $scope.arr="这是一个技术更新迅猛的年代!"; }); app.filter('cutTxt', function () { return function (value, max,tail) { var judgeLength = 0,cutString = new String(); var re = /^[u4E00-u9FA5]$/; if (!value){ return '' }; max = parseInt(max); for (var i = 0; i < value.length; i++) { if (judgeLength >= max) { cutString = cutString.substr(0, cutString.length-1); cutString = cutString.concat(tail||".."); return cutString; } var singleChar = value.charAt(i); if (re.test(singleChar)) { judgeLength+=2; console.log(singleChar); } else{ judgeLength++; } cutString = cutString.concat(singleChar); } return cutString; }; }); </script> </html>
未限制长度时:
限制长度时:
//*********** 添加另一个方法 *********//
app.filter("formatStrFilter",function(){ return function setString(str, len) { if(str==null){ return ""; } var strlen = 0; var s = ""; for (var i = 0; i < str.length; i++) { if (str.charCodeAt(i) > 128) { strlen += 2; } else { strlen++; } s += str.charAt(i); if (strlen >= len) { return s+"..."; } } return s; } })