Elamparithi doodleblue Elamparithi doodleblue - 2 months ago 21
jQuery Question

How to find string with last letter in angularjs?

I want to search a string using AngularJS by last character of the string. I have done search with first letter. I tried

lastIndexOf()
and endswith, but I can't get the result.

This one is working fine and its for first letter searching in a string .



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>




Answer Source

You can use the endsWith() method to test the last character of a string:

endsWith() determines whether a string ends with the characters of a specified string, returning true or false as appropriate.

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>