Strip quotes off of a Mongo regular expression

Is there a way to remove the quotes from the $regex objects shown below?

{ '$or': 
    [ '{"last":{"$regex":"/.*Pat.*/"}}',
      '{"first":{"$regex":"/.*Pat.*/"}}' ],
      thing: 57b713625bf9b85ca824de8c }

I attempted the following approach, but it doesn't work and I believe there must be a more efficient solution because I am unable to figure out how to assign an expression as the value of an object.

for (var key in req.query) {
if (req.query.hasOwnProperty(key)) {
  if (key === '$or') {
    for (var item in req.query[key]) {
      if (req.query[key].hasOwnProperty(item)) {
        req.query[key][item] = JSON.parse(req.query[key][item]);
        for (var x in req.query[key][item]) {
         for (var thereMustBeABetterWayToDoThis in req.query[key][item][x]){
           req.query[key][item][x][thereMustBeABetterWayToDoThis] = req.query[key][item][x][thereMustBeABetterWayToDoThis].replace(/["']/g, "");
         }
        }
      }
    }
  }
}

Answer №1

Looking to globally replace "$regex" with $regex, eliminating the unnecessary "? One approach could be to stringify the JSON, perform a regex replacement, and then parse the JSON again. While this method may seem straightforward, its efficiency in terms of performance remains uncertain.

Consider this example:

var test = { '$or': 
[ '{"last":{"$regex":"/.*Pat.*/"}}',
  '{"first":{"$regex":"/.*Pat.*/"}}' ],
  thing: 57 }
var test_string = JSON.stringify(test); //Convert it into a string.

var re = /\\"\$regex\\"/g;
var output = test_string.replace(re,"$regex"); //Do a simple replace 

var outputObj = JSON.parse(output); //Parse the object.

//Proceed with working on the outputObj

The key is in this regular expression - \\"\$regex\\". For a deeper understanding of how this regex functions, feel free to explore this basic demo which also doubles as a testing ground for customizing the regex to better suit your requirements.

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

Is there a way to ensure a box remains fixed on the edge of a browser window?

Looking to create a tooltip div that pops up next to and aligns with the top of a specific input element when it is clicked: lorem ipsum dolor ____________ ___________________ | this | [_button____clicked_] | appears | | on s ...

Bootstrap Tags Input is unable to function properly with data stored locally

I am currently working on developing a Project Manager tool that allows for the addition of multiple individuals to a single project. To accomplish this, I decided to incorporate the use of Bootstrap Tags Input by following the examples provided for Typeah ...

Merge two arrays together and pad with zeros where they do not overlap

Looking for help with combining two arrays containing datetimes and displaying the values on the x-axis of a chart. In need of a function that merges the arrays into one, adding a '0' where there are no duplicates. array 1 = [2016-01-20,2016-01 ...

How can I insert a button into a Flatlist using React Native?

Is there a way to add a single scrollable button inside a FlatList without duplicating it? I've been experiencing issues where adding a button inside the FlatList results in multiple buttons being displayed. On the other hand, placing the button outs ...

"Troubleshooting: State array in ReactJS/NextJS not rendering correctly following setState

I am facing challenges with rendering my objects using .map() within React / NextJS. Within my code, I have a function where I retrieve images from Firebase Cloud Storage as shown below: getImages = () => { let firebase = loadFirebase() ...

JavaScript's Selenium method for retrieving the attribute of an element

To best illustrate the issue I'm facing, a visual reference of what I am attempting to retrieve is necessary: https://i.sstatic.net/yVsiJ.png My current challenge lies in obtaining the source node of data, specifically using the path 'data.sour ...

Issue with jqGrid when filtering small numerical values

Happy Holidays! I recently came across an issue while trying to filter small numbers using jqGrid. I am filtering numbers that can vary from 10 to 1, down to values as small as 10^(-8) or even smaller. The filtering works well for these numbers until they ...

Issue with displaying mootools tooltips on Request.HTML content

I am encountering an issue with incorporating tips into a Request.HTML function. I have a div that updates its content every 30 seconds. The returned content consists of multiple divs with the class ".liveReader". Below is the JavaScript code used to init ...

How to Revalidate a Next.js Dynamic Route Manually Using an API Route?

In my application built with Next.js, I have a dynamic page that displays resources at the route /resource/[id]. When a user edits a resource, such as #5, I want to refresh the cached page at /resource/5. I've created an API route in my /pages direct ...

Angular 2 sidebar icons appearing vertically instead of in a row

Greetings! I've been struggling for hours to display a sidenav using Angular 2, with links listed as rows. Here is what my current setup looks like: https://i.sstatic.net/fmmAR.jpg Here is the code I've been working on: <md-sidenav-containe ...

<a href> click here to append a new query parameter to the existing ones

Is there a way to create a link that will add a query parameter to the current URL instead of replacing all existing ones? Here's what I'm looking for: If the current URL in the browser is example.com/index.html, clicking on it should lead to ...

What is the best way to cancel Interval in a React application?

I need help with implementing setInterval in my react redux application. Below is the code snippet from FileAction.js export const SetPath = ({ path, location }) => async (dispatch) => { try { let interval; if (pre_path === path) ...

Tips for refreshing the modified toggle in angular2

I currently have a newsletter subscription that is initially set based on the newsletter I receive when the user logs in. However, when I toggle the newsletter option, I receive a "successfully updated" message but the newsletter remains set to false even ...

Is it possible to pass function attributes through a single function in Javascript?

I'm currently trying to determine the most effective method to indicate that the game has ended. I have my gameover() function function gameover(chk, scoreOne, scoreTwo) { if (chk === true) { // Game over // Displ ...

Ways to prevent npm script from running automatically in the background

When working with npm scripts, I have a situation where some tasks need to run in parallel. My setup looks something like this: ... scripts: { "a": "taskA &", "preb": "npm run a", "b": "taskB" } ... Everything works well so far! But I am won ...

The Firebase signInWithPopup functionality suddenly shuts down in a Next.js project

Incorporating the signInWithPopup function for signing in has been successful during the development stage on my local server. const firebaseAuth = getAuth(app); const provider = new GoogleAuthProvider(); const [{ user, cartShow, cartItems }, dispatc ...

AngularJS: Importing a parent directive within a child directive

Take a look at this Plunk example to understand better. I'm attempting to create a test scenario for accessing complex directives, but I encounter an error when trying to call a method from the parent directive: Parent Directive app.directive(&apos ...

How to retrieve information from an Angular 2 subscribe method

Here is my Objective. @Component({ selector: "data", template: "<h1>{{ fetchData() }}</h1>" }) export class DataComponent{ this.http.get(path).subscribe({ res => return res; }) } In the scenario where fetchData was in ...

Numerous clocks on display

I am trying to display two clocks on my webpage, but for some reason only one clock is showing up. The first clock script is as follows: <script type="text/javascript"> var tmonth=new Array("January","February","March","April","May","June","July"," ...

Maximize Readings or Additions

At our company, we manage a vast mongodb collection containing millions of merchants and billions of products. When a merchant decides to go hidden, their products should no longer be visible to the public. I am currently exploring the most effective way ...