我想通过字符串的最后一个字符使用AngularJS搜索字符串。我用第一个字母做了搜索。我试过lastIndexOf()
并以此结束,但我无法得到结果。
这个工作正常,用于首字母搜索字符串。
var app = angular.module('filterSample', []);
app.controller('filterCtrl', function($scope) {
$scope.data = {
messages: ['first', 'second', '3rd', 'fourth', 'fifth']
}
$scope.startsWith = function(actual, expected) {
var lowerStr = (actual + "").toLowerCase();
return lowerStr.indexOf(expected.toLowerCase()) === 0;
}
});
<!doctype html>
<html ng-app="filterSample">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js">
</script>
<script src="example.js"></script>
</head>
<body>
<div ng-controller="filterCtrl">
<input type="text" ng-model="search" />
<ul border="1px" ng-repeat="msg in data.messages | filter:search:startsWith">
<li>{{msg}}</li>
</ul>
</div>
</body>
</html>
答案 0 :(得分:1)
您可以使用endsWith()
方法测试字符串的最后一个字符:
endsWith()
确定字符串是否以。结尾 指定字符串的字符,返回true或false 合适的。
var app = angular.module('filterSample', []);
app.controller('filterCtrl', function ($scope) {
$scope.data = {
messages: ['first', 'second', '3rd', 'fourth', 'fifth']
}
$scope.startsWith = function (actual, expected) {
var lowerStr = (actual + "").toLowerCase();
return lowerStr.endsWith(expected.toLowerCase());
}
});
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<div ng-app="filterSample" ng-controller="filterCtrl">
<input type="text" ng-model="search" placeholder="Search by last char" />
<ul border="1px" ng-repeat="msg in data.messages | filter:search:startsWith">
<li>{{msg}}</li>
</ul>
</div>
答案 1 :(得分:0)
只需更改您要查找的索引
$scope.endsWith = function (actual, expected) {
var lowerStr = (actual + "").toLowerCase();
return lowerStr.indexOf(expected.toLowerCase()) === (lowerStr.length - 1);
}
答案 2 :(得分:0)
您可以使用charAt
var lastChar = myString.charAt(myString.length-1);