What is the method for comparing array elements to a regular expression in this particular scenario?

My array contains strings with a specific format:

obj-meta_version-11_info
obj-meta_version-12_info
obj-meta_version-13_info

I need to loop through this array to identify objects that adhere to this naming convention. I think the regex pattern should be something like this:

obj-meta_version-([\d .]+)_info

Here's an example of what I'm trying to accomplish:

    for(let i=0; i<body.length; i++){
      if body[i].name = obj-meta_version-([\d .]+)_info {
         // do stuff
      }
    }

How can I correctly rewrite this if statement in JavaScript to utilize the regex? I have a background in Python, so I'm not quite sure how to do this.

Answer №1

Here is a potential solution for your code:

const body = [
  {name:'obj-meta_version-11_info'},
  {name:'wrong'},
  {name:'obj-meta_version-12_info'},
  {name:'obj-meta_version-13_info'},
  {name:'wrong again'},
];

for(let i=0; i<body.length; i++){
  if (body[i].name.match(/obj-meta_version-([\d .]+)_info/)) {
      console.log(body[i]);
  }
}

Sample output would be:

{ name: 'obj-meta_version-11_info' }
{ name: 'obj-meta_version-12_info' }
{ name: 'obj-meta_version-13_info' }

Changes made:

  1. Enhanced the condition in the if statement by adding ( and )
  2. Enclosed the regular expression in / for creating a RegExp object to match string patterns
  3. Applied the regular expression to the name field of each object

Keep in mind, the [\d .] part may need review. It currently matches one digit (0-9), a space character, or a dot. Consider \d+ for one or more digits instead.

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

The issue lies in the error code TS2315 which states that the type 'observable' is not a generic

I keep encountering an error message that says 'observable is not generic' while importing files. I am working on implementing CRUD operations in Angular 7, where I have created two components for adding and listing employees. The functions for c ...

Transmitted only JSON data instead of using multiform data with jQuery Ajax

When I use jQuery Ajax to send a JSON object, it ends up being interpreted as 'multiform' instead of pure JSON. How can I make sure my request is sent as a pure JSON object and not multiform? var demo = new Array("One", "Two", "Three"); $.ajax ...

Identify duplicate values in an array by comparing pairs of elements

If the array contains the data shown below: let array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 }, { name: "Suresh", SalseVersion: 12, MarketingCode: 13 }, { name: "Siva", SalseVersion: 10, MarketingCode: 14 }, { na ...

"JQuery's selector is failing to locate elements once they have been loaded through an

I am facing an issue where jQuery selectors are not working on elements loaded from the server via Ajax requests, but they work fine in normal mode. $('#myid').change(function(){ alert('OK!'); }); <select id="myid"> <optio ...

Simple Timer App with Vanilla JavaScript

Hey there! I am a newcomer to JavaScript and recently joined the stackoverflow community. Currently, I am working on a project called Pomodoro Timer with the goal of creating something similar to this example: http://codepen.io/GeoffStorbeck/full/RPbGxZ/ ...

How can I retrieve elements from an array that match a certain criteria and update the corresponding objects in

When an array contains matching IDs, the goal is to merge these objects into one object without affecting the original array. The current code only returns matching objects, but the expected result should combine them as described. main.ts const arr = [{ ...

Issues with pagination and navigation in Joomla when using the Swiper JS carousel with Bootstrap 5

Initially, I attempted to incorporate Swiper JS into my Joomla 4 template using Twitter Bootstrap 5. I connected it from CDN. If you visit this link: , you will see the desired layout from a Figma design: Screenshot However, I encountered some issues: A ...

Fetching JSON object from a node.js/express server using AJAX request

I've implemented server-side code to fetch data from an external website and return a JSON object to the client side of my node.js/express application. The intention is to further process this JSON on the client side. Within my index.js file, I have ...

Tips for retrieving multiple values or an array from an AJAX request?

Is there a correct way to pass multiple sets (strings) of data back after executing an ajax call in php? I understand that echo is typically used to send a single string of data back, but what if I need to send multiple strings? And how should I handle th ...

Creating markers for every value in a table using Google Maps API v3

Looking for some guidance here. I have a table with multiple values that I need to process using a function. Could someone help me with a suitable loop in jQuery or JavaScript that can achieve this? I'm still learning the ropes of these languages. My ...

Switch up the side navigation panel display

Hello, I am a newcomer to bootstrap and I have successfully implemented a collapsing navbar. However, I am looking for a way to make the navbar slide out from the right side when clicked on in mobile view. Can someone provide me with some JavaScript or j ...

A guide on integrating a submission button that combines values from multiple dropdown forms and redirects to a specific URL

Is there a way to make the submit button on this form act based on the combined values of two different dropdown menus? For instance, if "west" is selected from the first dropdown and "winter" is selected from the second dropdown, I want it to navigate to ...

Troubleshooting Issue with Internet Explorer failing to update Asp.Net MVC3 Partial View

I am experiencing an issue with a page that includes a div for a partial view loaded via an ajax request. $.ajax({ url: 'CompleteSessions', success: function (data) { var selector = $('#complete-session-sect ...

Authenticating the identity of the client application - the client is currently within the browser

I have a PHP backend (although it's not really important) and a Javascript client that runs in the browser. Here is how the application operates: The user accesses a URL and receives raw templates for rendering data An Ajax GET query is sent to the ...

What is the best way to show an SVG icon in React without having to make an HTTP request for the file?

A special requirement for a react application is to display icons in certain parts of the application while offline. The use of inline svg is particularly fitting for this purpose. import React from 'react'; // Utilizing inline svg to showcase i ...

The font family of Material-ui ToolbarTitle is no longer retained

https://i.sstatic.net/ygdwe.png The tutorial mentioned that the title should be styled with the Roboto font, just like the Options title above. However, despite including the Roboto font via a CDN in my project, the font does not appear as expected in my o ...

Form validation using jQuery and AJAX

I've implemented validation in my ResetPassword function and it seems to be working fine. However, I'm facing an issue where the ResetPassword function stops working once the validation is added. Can someone guide me on how to resolve this issue? ...

Troubleshooting the issue of 'is not a function' in browsers when using TS Namespaces

Currently diving into the world of TypeScript, I've embarked on the journey of organizing my code into separate files. My primary file is structured as follows: // calculator.ts namespace Calculator { console.log(Calculator.operate(1,2,"+")) } In ...

Use ng-class in a P tag to assess a variety of expressions

Is there a way to apply ng-class to automatically evaluate negative values within a < p > tag? <p <strong>LW$:</strong> {{d.lw_metric}} <strong>LW:</strong> {{d.lw_metric_percentage}} <strong>L4W:</strong> {{ ...

Prevent repetitive content on your Node.js server

After realizing my small image hosting has many duplicate content, I am looking for a solution to prevent this issue in the future. My idea is to use either checksum or hash code so that whenever a new file is uploaded, it will be hashed and compared with ...