2017-08-28 117 views
2

我想通过字符串的最后一个字符使用AngularJS搜索字符串。我用第一封信完成了搜索。我试过lastIndexOf()和endswith,但我无法得到结果。如何在angularjs中查找带有最后一个字母的字符串?

这一个工作正常,它的第一个字母搜索字母。

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>

+1

可使用内建的功能[String.prototype.endsWith()](https://developer.mozilla.org/ en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith)和[String.prototype.startsWith()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith) – Satpal

+0

可能的重复[How我可以使用JavaScript获取字符串的最后一个字符](https://stackoverflow.com/questions/5873810/how-can-i-get-last-characters-of-a-string-using-javascript) –

+0

谢谢Satpal和Tim Biegeleisen –

回答

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>

+0

感谢您的回答 –

0

只是改变你在找什么指数

$scope.endsWith = function (actual, expected) { 
    var lowerStr = (actual + "").toLowerCase(); 
    return lowerStr.indexOf(expected.toLowerCase()) === (lowerStr.length - 1); 
} 
+0

非常感谢您的回答 –

0

可以使用的charAt

var lastChar = myString.charAt(myString.length-1); 
+0

非常感谢您的回答 –

相关问题