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

Converting a string into a regular expression using JavaScript

I am attempting to change the color of a text element when specific variations of the word "hello" are entered into an input field. While this works with a regular string comparison, it fails when using a regular expression. <input id="input" type="inp ...

What could be the reason for the variable not resetting in my event handler?

Check out the code I've written below: $(document).ready(function () { var default_var = 2; var show_var = default_var; var total_var = 8; var increment_var = 2; var start_var = show_var+1; var end_var = show_var+increment_v ...

Is it possible to adjust the center of rotation in THREE.js TrackballControls so that it is not located at the center of the canvas

I'm currently using TrackballControls within THREE.js. The issue I am facing is that the center of rotation always remains in the center of the canvas. Is there a way to adjust this and move the center of rotation upwards? Here are my failed attempts: ...

Keeping data external to promises in protractor

In my angular app, I have a timeline feature that displays the names and descriptions of players. All player names are under the common class player-title.ng-binding, while all player descriptions share the class .player-description.ng-binding To retrieve ...

I am constantly reminded by React hooks to include all dependencies

Imagine I am using useEffect to pre-fetch data upon initial rendering: function myComponent(props) { const { fetchSomething } = props; ... ... useEffect(() => { fetchSomething(); }, []); ... ... } My linter is warni ...

Using AJAX to connect the JSP page with the Servlet's doGet() function for interaction

Currently, I am working on the JAVA code provided below in order to make a call to the servlet's doGet() method from a JSP page using an AJAX request. This is how my AJAX call looks like: I am passing the clicked text captured by ng-click of Ang ...

TreeView Filtering

I have encountered an issue while trying to utilize a treeview filter. Below is the method I have created: var tree = [{ id: "Tree", text: "Tree", children: [ { id: "Leaf_1", text: "Leaf 1", childre ...

What is the best way to retrieve seat number upon clicking in React Native?

I have implemented a for loop and assigned its value in the click function to retrieve the seat number when a seat is clicked. However, I am only getting the last number of the for loop every time a seat is clicked. Can someone guide me on how to obtain th ...

Type of Data for Material UI's Selection Component

In my code, I am utilizing Material UI's Select component, which functions as a drop-down menu. Here is an example of how I am using it: const [criteria, setCriteria] = useState(''); ... let ShowUsers = () => { console.log('Wor ...

Ways to reveal concealed div elements when hovering the mouse?

Is there a way to display a group of hidden div's when hovering over them? For instance: <div id="div1">Div 1 Content</div> <div id="div2">Div 2 Content</div> <div id="div3">Div 3 Content</div> All div's sho ...

Is it possible to have the front-facing photo in expo-camera stay mirrored?

Currently, I am utilizing the expo-camera library to capture a selfie image. Despite the preview being mirrored, the final saved image reverts to its normal orientation. Is there any way to avoid this behavior so that the image remains mirrored? Alternativ ...

Traverse through the loop with React Material UI in JavaScript

Hi everyone, I'm having trouble with this code. I want to iterate through an object called paleogenome.data and create a CardHeader for each item: { Object.keys(paleogenome.data).forEach(function (key){ console.log(paleogenome.data[key] ...

Vue Router generates a URL containing %2F when dealing with slug routes

I am facing an issue in my Vue 3 application where I need to create a route for dynamic slugs. Currently, when using RouterLink, the generated URL contains %2F instead of actual slashes which is not the desired result. For example, the current URL looks l ...

Express and Webpack Error: "SyntaxError: Unexpected token <"

I am facing difficulties while testing my React webpage that I built using Webpack. When trying to run an Express server, the localhost page appears blank with a console message saying Uncaught SyntaxError: Unexpected token <. It seems like the webpage ...

Encountering difficulties when attempting to inject NotifierService into an Angular Service

I am attempting to incorporate Angular NotifierService into my service class so that I can display error notifications in case of any exceptions from the service side. I attempted to inject a bean of NotifierService in the constructor of my service class, ...

Running JavaScript code on a webpage using Selenium

I'm currently developing an automated script to enter a person's address details on a webpage. It's important to note that I did not create this webpage myself. While filling in the address details, I encountered an option to select the coun ...

Troubleshooting problems with data binding in Angular Ionic

Just starting out with Angular and experimenting with building an app in Ionic. I have a screen with 2 input fields and I want to achieve the following. When a user inputs something in the price field, I want the weight field to update accordingly. Simil ...

Leveraging the browser's console for transmitting AJAX data

I've created a PHP quiz page that uses AJAX to post answer data when a user clicks on an answer. If the answer is correct, the page then loads the next question using another AJAX function. Here's a snippet of the code: <ul class="choices"> ...

Running Grunt task after saving in NetBeans 8.0 - A step-by-step guide

In my Maven Spring MVC project within NetBeans 8.0, I am utilizing AngularJS for front end development. With over 30 .js files and counting, I decided to streamline the process by using Grunt to merge and minify them. After installing Node.js, npm, and gr ...

Trouble with AngularJS Smart Table when dealing with live data streams

Currently, I am facing a scenario where I am utilizing angularJs smart table for filtering. Here is the HTML code: <section class="main" ng-init="listAllWorkOrderData()"> <table st-table="listWorkOrderResponse"> <thead> ...