Hi I've got follow code
HTML:
<div ng-app="myApp" ng-controller="myController">
<input ng-model="value">
<button ng-click="checkValue()">Check value</button>
</div>
Controller:
angular.module("myApp", []).controller("myController", function($scope) {
$scope.value = '';
$scope.acceptedValuesList = {
"Items": [{
id: 1,
name: 'MI'
}, {
id: 2,
name: 'MO'
}, {
id: 3,
name: 'AB'
}]
};
$scope.checkValue = function() {
if (acceptedValuesList.Items.find((item) => item.text == $scope.value)) {
console.log("accepted value");
} else {
// SANITIZE VALUE UNTIL IT'S CORRECT
}
}
});
When I write one of the string, which are in my array ('MI', 'MO' or 'AB') in the input and click on the button, it searches for the string in my list and if the value in the input matches with one of the three string, I print a little message in my console. This works fine. So know I would like to sanitize my value in the input, if there is also another letter. For example, when I wirte "ABx" into the input and press the button, it should remove the "x" and show "AB" in the input. How can I do this? I didn't find anything, that could help me. I hope this is clear enough. Thanks.
EDIT: MY OWN SOLUTION:
This is my solution: I write a value in my input field: input value = xyAbs;
First of all I use toUpperCase() to ignore case sensitive.
Than I loop throught my list with find() and search for my value in the current looped item.
$scope.value.toUpperCase(); // $scope.value = 'XYABS'
let item = $scope.acceptedValuesList.Items.find((item: any) => $scope.value.search(item.name) >= 0); // item = object in the list with id = 3 and name = 'AB'
After that, I check if there was an item found, so my value in the input is in one of my items in my list. Than I use substr() to get the substring in the value from the position where it starts with the length of the name. After that I get my string. If there was no item found, so my string is wrong, I clear the input:
if(item) {
$scope.value = $scope.value.substr($scope.value.search(item.name), item.name.length); // $scope.value = 'AB'
} else {
$scope.value = '';
}
This works fine for me, I hope it's clear enough. Thanks. :)
if(string.search("MI") { console.log("ITS MI"); } else if(string.search("MO") { console.log("ITS MO"); }