Experimenting with a custom AngularJS filter designed to extract numerical values from a chunk of text

I am working on creating a unique filter that can extract numbers from text input into a text box. For example:

User enters: The cat went to 4 stores and bought 3 bags of cat litter for 1 dollar.

The desired output would be: [4, 3, 1]

This filter works by analyzing the previously filtered array ['the', 'cat', 'went', 'to', '4' ...]

My approach involves utilizing a for loop to iterate through the array and identify numerical values. However, uncommenting the for loop causes issues within the application. Any suggestions or assistance would be greatly 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;
      };

  })

Answer №1

If I were to modify the filter, it would look something similar to this example:

javascript

.filter('showNumbers', 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 | showNumbers }}</p>
  </body>

http://example.com/filter

Answer №2

It seems like wZVanG provided a helpful solution for your function by incorporating regular expressions while maintaining the signature of the filter to ensure it returns an array of integers and accepts an array as input.

 filter('showNum', function() {    
    //This filter extracts numbers from an array
        return function extractNumbers(input){
        var numArray = [];
        var stringArr = input.toString();

        var numberStrings = stringArr.match(/\b\d+\b/g);

       numberStrings.forEach(function(str){
           numArray.push(parseInt(str));
       });

       return numArray;

 })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for preserving login session continuity following page refresh in Vuejs

signInMe() { this.$store.dispatch('setLoggedUser', true); this.$store.dispatch('setGenericAccessToken', response.data.access_token); this.errorMessage = ""; }, (error) => { if (error) { th ...

Exploring the functionality of Array.prototype.includes() in Angular 7 with PhantomJS testing

While testing components in my Angular application, I noticed that unit tests utilizing Array.prototype.includes() are successful in Chrome but fail when executed with PhantomJS. I found some suggestions in the responses to this question related to a simi ...

The use of asterisk (*) in importing dynamically

Hello everyone, I'm currently working on a project structure that looks like this: intranet ├── modules │ ├── storage │ │ ├── views │ │ └── route │ │ └── index.js │ │ │ ├── ...

Tips for creating a responsive Youtube embedded video

Check out this website for a good example: If you take a look, you'll notice that the header youtube video is responsive - it automatically resizes when the window size changes. Here are the <iframe> codes: <iframe id="bluetube-player-1" fr ...

Retrieving a result from a function call is a fundamental aspect of programming

I have a scenario where I am initiating a call from a controller within AngularJS. This call passes some data to a service in order to receive a response that needs to be conditionally checked. Controller patents.forEach(function(item){ // The "patents" ...

"The orderBy function in AngularJS seems to be overlooked or not functioning properly within the

It seems like the orderBy function is being ignored in my code. Despite adding a console.log for testing purposes, the function doesn't appear to be called at all. As a result, the data is still displayed but remains unordered. Snippet of HTML Code ...

Recently updated to the latest versions of Angular, AngularCLI, and Rxjs (version 6), however encountering an error stating "Property 'take' does not exist on type 'Observable'"

Recently, I made the decision to update my Angular5 project to Angular6 and upgraded all dependencies along with it (such as rxjs now at version 6 and angular-cli). However, I have encountered a problem that is proving difficult to resolve: ERROR in src/ ...

Exploring the blend of HTTP requests and personalized promises in AngularJS through recursive functions

I recently created a function wrapper that serves cached HTTP responses, but I'm encountering an inconsistency in one specific scenario (indicated by the comment // <--HERE). The issue seems to be related to the cache expiration not waiting for the ...

Saving a revised JSON file using AngularJS

Currently, I am in the process of developing a phonegap application using AngularJS that relies on a .json file to store an array of entries. The main goal I am aiming for is to enable users to mark specific entries as favorites and then utilize that data ...

When you try to remove an element from an array by its index in Vue JS, the outcome may not be

Here is an array that I have: var hdr = ("name", "date", "start_time", "selling_item", "total_call", "end_time", "ad_num", "area", "order_num"); //this data comes from the database Now, I need to rename these array elements according to prope ...

Prevent the creation of nested objects in Django Rest Framework

Hello there, I need assistance on how to prevent the creation of nested objects within my serializers. Here is an example of my serializer setup: class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = (&a ...

The web server is now serving Index.html instead of main.js for AngularJS 2

Transitioning from an angular1 application to an angular2 one, I encountered an error after removing the ng-app directive and adding the system.config: Error: SyntaxError: Unexpected token < Evaluating https://localhost:8080/contents/app/main.js Error ...

transforming basic pagination using javascript to jquery implementation

I have a straightforward pagination code written in raw JavaScript. function UpdatePage(e){ if(busy == 0) { switch(e) { case "Next": page = p+1; p++; break; ca ...

Merge nested arrays while eliminating any redundant elements

Is there a way to merge these array sets while ensuring that duplicate values are removed? I am unsure if lodash provides a solution for this specific scenario where the arrays are nested. Most of the solutions I have come across assume flat arrays. Any ...

Use JavaScript to add a div element to the page ten times every time the button is clicked

Here is the code I have written: $(document).ready(function () { $('<button class="btn more">View More</button>') .appendTo(".listing-item-container") .click(function() { $(this).closest(". ...

Guide to deactivating an input field in an angular js smart search dropdown

I'm struggling to figure out how to disable or make an input field read-only for AngularJS. The issue is that users are entering values not available in the dropdown list. Previously, I attempted using the disable property, but this ended up disablin ...

Adding the API JSON response to the MetaInfo in Vue.js

i am dealing with a meta tag that has the following structure metaInfo () { return { title: 'my title', meta: [ { name: 'description', content: 'my description' }, ...

The error "Unable to create an instance of mssql.Schema" indicates that the

Seeking assistance from experienced ReactJS developers to address the issue outlined below. The code provided is based on a tutorial I was following. Despite numerous attempts, I have been unable to resolve the issue. Here is the code snippet from User.js ...

Managing Server Crashes in Node.js

Is there a way to automatically update the database whenever my node.js server crashes or stops? Similar to how try{}catch(){}finally(){} works in JAVA. I am new to this. Does Node emit any events before shutting down so that I can run my function then? ...

Angular is the best method for properly loading a webpage

Struggling to solve this issue. I have a webpage where I need to load another webpage, specifically a page from a different site, into a div. Essentially, it's like a news ticker that I want to showcase. The problem is that the URL is stored in a Mon ...