2017-08-28 13 views
2

文字列の最後の文字でAngularJSを使用して文字列を検索したいとします。私は最初の手紙で検索を行った。私はlastIndexOf()とendswithを試しましたが、私は結果を得ることができません。anglejsの最後の文字で文字列を見つける方法は?

この文字列は、最初の文字が文字列で検索されていて、うまく動作しています。

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

使用を使用することができます(https://developer.mozilla.org/ 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()文字列がで終わるかどうかを判断する指定された文字列の文字は、真または偽を として返します。

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

あなたはビルド中に関数[String.prototype.endsWith()]のcharAt

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

お返事ありがとうございます –

関連する問題