Using Regular Expressions to Filter Arrays of Objects in Angular Versions 5 through 9

How do I use RegExp to filter objects, including title, email, and name?

Title and name must contain only alphabetic characters. The email must be valid.

RegExp Patterns:

Email = /[a-zA-Z0-9.-]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}/

Title & Name = /^[A-Za-z]+$/

If any email is invalid, store it in a separate variable and store the other objects in a different variable.

In JSON, if the first object's email is invalid, it should be stored in a separate variable.

items = [
{
    title: "This is a title", 
    email: "test@test.com",
    status: "confirmed"
},
{
    title: "Another title", 
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0774686a626869624774686a62736f6e6e69605964686a">[email protected]</a>",
    status: "pending"
},    
{
    title: "Just some text", 
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa979fba83958fd49995d48f91">[email protected]</a>",
    status: "pending"
}
]

Answer №1

Can you please give this strategy a try?

var items = [
{
    title: "This is title", 
    email: "testtest.com",
    status: "confirmed"
},
{
    title: "This another one", 
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="71021e1c141e1f1431021e1c140519181f165f121e1c">[email protected]</a>",
    status: "pending"
},
{    
    title: "Just a random string", 
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8de0e8cdf4e2f8a3eee2a3f8e6">[email protected]</a>",
    status: "pending"
}    
]

var filtered_not_matching = items.filter(s => !/[a-zA-Z0-9.-]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}/.test(s.email))

console.log(filtered_not_matching)

The .test() method checks for a pattern match between a regular expression and a string.

I recommend looking into the below article on regex matching in JavaScript as it covers various APIs related to regex matching:

Answer №2

If you're looking to refine your email filtering process by applying a regex rule to eliminate invalid emails, you can utilize the Array.filter() method on the items array. This method will help you weed out any objects whose email does not comply with the specified regex pattern. You have the flexibility to use various matching techniques such as text or match for your regex evaluations.

Here's a practical example of how this can be implemented:

const items = [{
    title: "This is title",
    email: "testtest.com",
    status: "confirmed"
  },
  {
    title: "This another one",
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9aab6b4bcb6b7bc99aab6b4bcadb1b0b7bef7bab6b4">[email protected]</a>",
    status: "pending"
  },
  {
    title: "Just a random string",
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab7bf9aa3b5aff4b9b5f4afb1">[email protected]</a>",
    status: "pending"
  }
];

const emailRegex = new RegExp(/[a-zA-Z0-9.-]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}/)
const titleRegex = new RegExp('/^[A-Za-z]+$/');

const res = items.filter(({
  title,
  email
}) => !email.match(emailRegex));
console.log(res)

const res2 = items.filter(({
  title,
  email
}) => !emailRegex.text(email));
console.log(res2)

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

Action creator incomplete when route changes

In my React-Redux application, there is an action creator that needs to make 4 server calls. The first three calls are asynchronous and the fourth call depends on the response of the third call. However, if a user changes the route before the response of t ...

What steps can I take to achieve complete code coverage in my unit testing for this component and also ensure that the 'else' part is being

I am struggling to figure out how to access the remaining line of code in order to achieve full code coverage. Simply checking if the function has been called (toHaveBeenCalled()) will suffice. Here is a snippet from my TypeScript file and Spec file, alon ...

Subclass callback with parameters

Having some trouble with one of my TypeScript functions and I'm hoping it's not a silly question. I believe what I'm attempting should work in theory. Here's a simplified version of my issue to demonstrate where the problem lies (the o ...

Inquiring about building a comprehensive AJAX website: SEO, Google index, design templates

I'm currently developing a fully AJAX-based website. My focus right now is on implementing page navigation and content display without the need for page reloading. Here's my approach: <html> <head> <!--CSS--> .hidde ...

What is the best way to implement a dynamic dropdown menu using react-bootstrap?

The react-bootstrap site provides an example code for forms, but I am struggling to find examples that utilize arrays to drive the options. <Input type="select" label="Multiple Select" multiple> <option value="select">select (multiple)< ...

Having trouble incorporating symbols with functionalities using HTML, CSS, and JS

I have implemented a table with three columns: "Action", "Question Subquestion/Text", and "Sort order". Additionally, I have incorporated a feature that allows for drag and drop functionality on the rows. Below is my code snippet: <!DOCTYPE html> &l ...

What exactly is the data type of setInterval in TypeScript?

If I want to define the type of a variable that will be used with setInterval in the following code snippet: this.autoSaveInterval = setInterval(function(){ if(this.car.id){ this.save(); } else{ this.create(); } ...

Is it Beneficial to Combine jQuery with TypeScript in Angular 7?

Our school project team is venturing into the world of Angular and TypeScript, but we all admit to being newbies in this area. I've mainly focused on the design aspect of our project and left the coding to my teammates. However, I recently completed ...

Navigating through Vue Router with Dynamic Imports and Guards

I am looking to dynamically bring in data from a component file into a router file, and then allow the use of next() based on the value of the imported data. In my App.vue file, I am using this.$router.push({name: "Dashboard"}) when the data changes from ...

A new issue arises after merging in Google Datastore, as an unexpected property is

Currently, I am working on developing an API in Typescript to interact with a Google Cloud Datastore instance for storing and retrieving entities. So far, I have successfully implemented the GET, POST, and DELETE methods. However, I encountered an issue w ...

Using async/await in combination with Vuex and Feathers

Please review my code below. I am attempting to integrate Async Await into vuex. While everything is functioning properly, I would like to call another action after this one using async await. However, the expected result is not being achieved as the conso ...

jQuery template does not respond to input text when a click event is enabled on an iPhone device

Below is a jQuery template I have: <div class="parent-class"> <div class="sub-class"> <div clas="sub-input-class"> <input type="text" /> </div> </div> </div> Recently, I ...

When Custom Route Provider is not a valid function

This question has been revised since this morning. I am working with two distinct modules, 'admin' and 'authorization'. Within the provider block of the authorization module, I utilize $routeProvider to add an identical route to all ro ...

Add HTML code into a contenteditable element and then include additional text following the inserted HTML

I'm working with a contenteditable div and a button that inserts a simple span. <button id="insert-span">Insert</button> <div id="edit-box" contenteditable="true"></div> <script> $('#insert-span').on(' ...

Exploring jQuery Mobile | Moving Seamlessly between Pages

I'm relatively new to JQM and I'm working on creating a mobile application using jQuery Mobile. Here's the goal I'm aiming for: I have multiple HTML pages, each with its own CSS, JavaScript, and JQM components. What I want is to be ab ...

Accessing the login page will not display the header, breadcrumb, or

I am currently utilizing the PrimeNG theme in conjunction with Angular. In order to create a login component containing a login form, I proceeded as follows: ng generate component login I then added the following to my app.routes.ts: import {Routes, Rou ...

Angular Forms, mark a form as invalid if a p-select element retains its original value

I am looking to prevent the submit button from being enabled until a user makes changes in any of the form controls. The challenge I'm facing is that while required input fields are easy to handle, there is also a select control with three options. De ...

I am encountering an error when trying to fetch a JSON response from a PHP script, even though I am able

Below is the Javascript code I am using to initiate an AJAX call from a PHP file: $(document).ready(function(e) { $(function(){ $.ajax({ type:'GET', dataType: 'jsonp', data: { ...

Tips for creating a vue-cli application that can be customized post-build:

I have a functioning vue-cli application that I can easily build. However, I now need to create a single deployable build that can be used on multiple servers. The challenge is that depending on the server, I will need to adjust some basic variables such a ...

The autosearch feature seems to be malfunctioning

I am currently working on implementing an autocomplete suggestion feature using the AutoComplete plugin from GitHub. I am using a combination of HTML, JavaScript, and CSS for this project. The functionality works perfectly when I hardcode the data in the f ...