1

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;
      };

  })
1
  • 1
    Using regular expression is more practical. "The cat went to 4 stores and bought 3 bags of cat litter for 1 dollar.".match(/\b\d+\b/g) returns 4,3,1 Commented Jun 20, 2015 at 13:32

2 Answers 2

1

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>

enter image description here

http://plnkr.co/edit/Hp91dIXbThzvnwzIFbVn?p=preview

Sign up to request clarification or add additional context in comments.

Comments

0

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;

 })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.