JavaScript: Using regular expressions to search for strings with or without quotes

I am trying to make the following functionality work in my code:

  • Searching for Carpenter Company should return 2 records
  • Searching for "Carpenter Company" (with quotes) should return 1 record

So far, I have not been successful in getting it to work. I also attempted to use regex with the expression:

"[\w\s]+\"

You can find a sample of my code on Plunker here:

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

I am specifically focusing on this part of the code:

    var app = angular.module('filter', [])
app.controller('MainController', function($scope) {
  $scope.deals = [{
    lob: 'Marine, Motor, Carpenter',
    cedent: 'ABC Paris Company',
    treaty: 'QS - Test'
  }, {
    lob: 'Liability',
    cedent: 'Carpenter Company',
    treaty: 'W/XL Test'
  }];
});

// filterBy implementation
app.filter('filterBy', function() {
  return function(array, query) {
    var parts = query  && query.trim().split(/\s+/g) ,
      keys = Object.keys(array[0]);
    if (!parts || !parts.length) return array;
    return array.filter(function(obj) {
      return parts.every(function(part) {
        return keys.some(function(key) {
          return String(obj[key]).toLowerCase().indexOf(part.toLowerCase()) > -1;
        });
      });
    });
  };
});

Any hints or suggestions on how to solve this issue would be greatly appreciated. Thank you!

Answer №1

To effectively gather the search keywords from the input, some modifications need to be made to the code:

app.filter('filterBy', function() {
  return function(array, query) {
    if (!query) return array;                    // Improved error checking by adding this line
    var parts = query  && get_query(query.trim()) , // Utilizing the get_query function in this section
      keys = Object.keys(array[0]);
    if (!parts || !parts.length) return array;
    return array.filter(function(obj) {
      return parts.every(function(part) {
        return keys.some(function(key) {
          return String(obj[key]).toLowerCase().indexOf(part.toLowerCase()) > -1;
        });
      });
    });
  };
});

function get_query(qry) {      // A function dedicated to gathering search keywords
  var re = /"([^"]+)"|\S+/g;   // This regex captures all "..." or non-whitespace substrings
  var m;                       // Initializing variable for storing matches
  var res = [];
  while ((m = re.exec(qry)) !== null) { 
    res.push(m[1] ? m[1] : m[0]);     // Pushing either captured text inside "" or a non-whitespace chunk into the results array
  }                                    // End of while loop

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

Employing passport-steam alongside sails-generate-auth

As I develop my SailsJS application, I am aiming for users to authenticate solely through Steam. I utilized `sails-generate-auth` to set up some boilerplate code with sails routes, but integrating passport-steam has proven challenging. If you are interest ...

Problems with implementing JavaScript code in a WebView

I am currently working on an android WebView project where I have managed to change the background color to orange with this code snippet. @Override public void onPageFinished(WebView view, String url) { wv.loadUrl("jav ...

Efficiently performing batch updates and inserts using Mongoose and Node.js

I am looking to manage and update a list of items in Node.js. The goal is to check if an item already exists, update it in the database, add it if it doesn't exist, and remove it from the database if it is in the database but not in the list. When se ...

Maximizing AngularJS functionality: Best practices for passing multiple parameters in routes

Currently, I am in the process of developing an application with AngularJs. I have encountered a challenge while setting up routing that involves sending multiple data in a route. Below is the code snippet for my route: .state('/filter-list', { ...

I'm having trouble getting this angular expression to cooperate in Plunker. Can anyone shed some light on why {{ 843 / 42

I'm currently diving into Angular with the help of Plural Sight. The initial lesson dives into utilizing the ng-app directive. For those interested, here's a direct link to the Plunker editor: http://plnkr.co/edit/HIDCS8A9CR1jnAIDR0Zb?p=preview ...

Screen the information passing through the Nivo Bar Chart

With react-table, I have successfully implemented data filtering but I am looking to enhance the dynamism of the filter. The current challenge lies in filtering the data displayed on a graph to make it more meaningful. I want to group products from the sam ...

Store the response token from a Request.post in a variable

To complete a URL, I only need to extract the token provided in the API response. The response body must be saved in a variable for later use. I am currently using Protractor for automated testing, and as part of this process, I need to consume an API tha ...

react-router-redux is unable to navigate to a different URL

I'm working on redirecting within a redux action when an error occurs. I attempted to utilize react-router-redux but encountered the following error. Uncaught TypeError: Cannot read property 'push' of undefined at middleware.js:29 a ...

Exploring TypeScript and React Hooks for managing state and handling events

What are the different types of React.js's state and events? In the code snippet provided, I am currently using type: any as a workaround, but it feels like a hack. How can I properly define the types for them? When defining my custom hooks: If I u ...

How can we dynamically extract the chosen value from a multiple selection using MaterializeCss?

(none of the similar questions provided me with a solution) Currently, I am utilizing the HtmlHelper @Html.ListBoxFor to generate a multiple select. However, I am encountering an issue where it generates the following structure: <ul id="select-option ...

Extract data from a webpage using Python and AJAX operations

With my knowledge of scraping HTML using Python's Beautiful Soup, I encountered a challenge with this soccer statistics page that utilizes AJAX to retrieve data on minutes played by a player. (I discovered the network call through firebug). I'm ...

Ways to control the number of boxes that are checked

I am currently working on a script to restrict the number of checkboxes that can be checked, but I am encountering an issue where the script is disabling all checkboxes on the page. Is there a way to only disable a specific checkbox within a certain div? ...

Incorporate concealed image into HTML

When I perform actions with a couple of images, I encounter delays because the browser needs to load the images. For example, if I use $('body').append(''); everything works smoothly without any delays. However, when I try using style= ...

Achieving second class using jQuery from a choice of two

Looking for assistance with retrieving the second class from an element that has two different classes. I attempted to use the split method but encountered some issues, can anyone provide guidance? js_kp_main_list.find('li#kp_r_04').addClass(&ap ...

Serialization of objects is not possible in Angular JS post requests

At the moment, I am utilizing an AngularJS Post method to send data to my controller instead of a traditional form submission. The issue I am encountering is that after the post call, the object named sharingInfo in the controller always gets set to null. ...

Puppeteer will not navigate to chrome://version when running in headless mode

Currently, I am utilizing the puppeteer.connect method to navigate to chrome://version in order to extract the user-agent being used by Puppeteer. Everything works fine when headless mode is disabled, but an error occurs when attempting it with headless mo ...

Tips for extracting information from a select box that is dynamically populating

I have a dropdown menu displayed in the image below. It contains a "More..." option that, when clicked, loads the next ten data items. Subsequent clicks on "More" will load another set of ten data items each time until the entire list is loaded. How can I ...

Manage InversifyJS setup based on the current environment

Recently, I've been utilizing InversifyJS to manage dependency injection within my TypeScript server. A current challenge I face is the need to inject varying implementations into my code based on the environment in which it is running. A common situ ...

Different methods to retrieve content within a div that is located on a separate, included page

It's a bit tricky to come up with a title for this topic, but essentially, I'm trying to figure out how to get content from an included page into a specific div using HTML and PHP. Let me break it down: In the header.php file, we have the follo ...

What is the best way to search for a variable number of aliases?

Suppose I have a GraphQL Schema structured as follows: Schema { user($id: ID) { id: ID name: String } } I am familiar with querying for a single user based on their unique ID. Utilizing aliases, I can also query for multiple users in the foll ...