Reputation: 164
What I would like to create is a filter which will pull the numbers out of text that is put in a text box. For example:
User types: The cat went to 4 stores and bought 3 bags of cat litter for 1 dollar.
Result would be: [4, 3, 1]
The filter will see because of a previous filter ['the', 'cat', 'went', 'to', '4' ...]
So what I tried to create was a for loop that would go through the array and check each item to see if it is in fact a number. However, the for loop breaks the app when it isn't commented out. Any help is appreciated.
filter('showNum', function() {
// this filter is not complete but it will return only numbers from an array
return function isNumeric(title){
var numbers, i, len, numberToAdd;
numbers = [];
len = title.length;
// for(i=0; i<len; i+=1){
// numberToAdd = title[i];
// if(!isNAN(numberToAdd)===False); {numbers.push(numberToAdd);}
return numbers;
};
})
Upvotes: 1
Views: 50
Reputation: 34207
I would change the filter to something like this:
javascript
.filter('showNum', function() {
return function(input) {
if (!input)
{
return [];
}
return input
.split(' ')
.filter(function(item){
return item && !isNaN(item);
})
.map(function(item){
return parseInt(item);
})
};
});
html
<body ng-controller="MainCtrl">
<input type="text" ng-model="input">
<p>result: {{ input | showNum }}</p>
</body>
Upvotes: 1
Reputation: 3402
wZVanG is correct, here is a revisit of your function using the regular expression but respecting the signature of the filter so that it returns an int array and takes an array as parameter.
filter('showNum', function() {
//this filter returns only numbers from an array
return function isNumeric(title){
var numbers, i, len, numberToAdd;
numbers = [];
var theString = title.toString();
var numbersAsStrings = theString.match(/\b\d+\b/g);
numbersAsString.forEach(function(s){
numbers.push(parseInt(s));
});
return numbers;
})
Upvotes: 0