When comparing MongoDB to Javascript, the $regex matching pattern yields varied results

Currently, I am implementing the following $regex pattern in a mongo query:

{domain: {$regex: '^(.+\.)?youtube.com$'}}

I anticipate that it will match youtube.com as well as sub.youtube.com.

However, the issue I have encountered is that it also matches values like justyoutube.com.

Interestingly, in JavaScript, the match does not occur:

console.log(/^(.+\.)?youtube.com$/.test('justyoutube.com'));
// This returns `false` as expected.

Do you have any suggestions on improving this functionality? Is the problem related to my regex itself, or is it due to the regex library utilized by MongoDB?

Update: I have noticed that utilizing /pattern/ instead of 'pattern' yields the desired outcome. However, I am still interested in finding a solution using quotation marks for easier debugging in MongoDB Compass.

Answer №1

It seems like the backslash in the string you're passing is working as an escape character within the string itself, rather than being included in the actual regular expression. One way to handle this is to double the backslash to effectively 'escape the escape':

const unescaped = new RegExp('^(.+\.)?youtube.com$')
const escaped = new RegExp('^(.+\\.)?youtube.com$')

console.log(unescaped.test('justyoutube.com'));
console.log(escaped.test('justyoutube.com'));

console.log(unescaped.test('sub.youtube.com'));
console.log(escaped.test('sub.youtube.com'));

// Another approach is to use a template literal, which interprets all characters literally:

const withBacktick = new RegExp(`^(.+\.)?youtube.com$`);
console.log(withBacktick.test('sub.youtube.com'));
console.log(withBacktick.test('justyoutube.com'));

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

Unlocking the Power of Large Numbers in Angular with Webpack

Error: [$injector:unpr] Unknown provider: BigNumberProvider Recently, I embarked on a new project using Webpack + Angular.JS and encountered an issue while trying to incorporate Bignumber.js. Here's a snippet of my Webpack configuration: resolv ...

The sendFile function fails to transmit any data

Currently working on integrating the mailChimp API into my project, but facing an issue with the resFile code that handles sending the success response. The current code snippet: async function run(){ try { const res = await mailch ...

React - a response data array gets cleared when it is assigned to state within a useEffect hook

When working with my MongoDB data storage, everything seems to be functioning properly. I have an endpoint set up for testing purposes and use the useEffect hook in my code to retrieve data from the database. The snippet of code in question is: const [pers ...

Leveraging JavaScript and HTML to extract a single data point from a JSON response

As a complete beginner, I want to clarify that I may not be using the correct terminology in my question. I am embarking on creating an HTML5/Javascript application with Intel XDK to retrieve barcode information for video games from an online API. Specifi ...

Customize Your Lightbox Fields with DHXScheduler

In my JSP application for exam timetabling, I have integrated DHXScheduler and customized the lightbox to display additional information about exams using my own fields. The EventsManager class is responsible for managing events by saving, creating, and r ...

Can you explain the distinction between data-ng and ng?

I recently came across a discussion about the distinction between ng-* and data-ng-* in AngularJS. Apparently, using data-ng-* ensures that the HTML remains valid. But I can't help but wonder, why is this necessary when I can simply declare the ang ...

Options for regular expressions in CSS: match letters regardless of case and search for all occurrences

Here is the HTML I am working with: <div> <img class="hi" src="http://i.imgur.com/f9WGFLj.png"></img> <img class="HI" src="http://i.imgur.com/f9WGFLj.png"></img> </div> Additionally, I have the following CSS co ...

If the option is not chosen, remove the requirement for it

I am in the process of creating a form that offers 3 different payment options: 1 - Direct Deposit 2 - Credit Card 3 - Cash at Office The issue I am facing is with the validation of input fields for Credit Cards. I want to make it so that these field ...

Preventing Duplicate Entries in NodeJS with Mongoose Database Integration

Currently, I am utilizing NodeJS with Mongoose to access an API and retrieve data. My Schema is structured as follows: var dataSchema = new Schema({ id:Number, name:String )); To insert data, I am using the code snippet below: var d = Data.find({i ...

Implementing a Basic jQuery Animation: How to Easily Display or Conceal DIV Elements Using fadeIn and fadeOut

SCENARIO: Include 2 links, MY INFO and LOG IN, within a list of ul, li elements. Hovering over one link should display a box with a form inside using the fadeIn animation. The other link should show a button in a box with a fadeIn animation when hovered o ...

Troubleshoot JavaScript in a Firefox browser extension

I have been developing a Firefox addon that relies heavily on JavaScript. The addon serves as a UI recorder with a popup window containing specific buttons that interact with a tab in the main window. When I try to debug the addon using the debugger in ei ...

What is the process of creating a new array by grouping data from an existing array based on their respective IDs?

Here is the initial array object that I have: const data = [ { "order_id":"ORDCUTHIUJ", "branch_code":"MVPA", "total_amt":199500, "product_details":[ { ...

Matching, verifying + retrieving (+ deleting) using preg_match_all

Currently in the early stages of learning regex, but making progress and experimenting! I am attempting to determine if a string ends with a space followed by a year between 1800 and 2100. If it does, the goal is to extract and remove that number from th ...

Leveraging Emotion API in Video Content (JavaScript or Ruby)

Currently, I'm in the process of uploading a video to the Emotion API for videos, but unfortunately, I have not received any response yet. I managed to successfully upload it using the Microsoft online console. However, my attempts to integrate it in ...

Is it possible to update the page title with JQuery or JavaScript?

Is it possible to modify the page title using a tag inside the body of the document with jQuery or JavaScript? ...

Transmit information across disparate components in Vue.js

This situation involves a Graph component displayed in the body of the page, allowing user modifications. Additionally, there is a Search component located in the header of the page. These two components are independent - Graph is exclusive to the body o ...

The JavaScript onClick function is unable to identify the object

"Newbie" JavaScript Question:-) I'm struggling with a JS function in my code: <script type="text/javascript"> $(function () { $('.shoppinglist-item-add').ShoppinglistItemAdd(); }); </script> This "shoppinglistI ...

Encountering issues with JavaScript/ajax if statement functionality

Driving me insane! Dealing with 2 modal forms - one for login and another for registration. Javascript handles client-side validation, followed by an ajax call to either a registration or login php file. The PHP files return 'OK' if successful or ...

When attempting to upload a file using ajax, the $_FILES variable in PHP came

I am facing an issue with uploading images via AJAX where my PHP is not receiving the AJAX post. function handleFileSelect(evt) { files = evt.target.files; // FileList object $('.thumb-canvas' + filesId).css('display','bl ...

What are some techniques for transforming text into JSON format?

Beginner inquiry: I'm struggling with manipulating text using JavaScript. Here is the text I want to transform: "5555 55:55: John: New York 6666 66:66: Jack: Los Angeles" My desired output after manipulation: [{ name:"John", address:"New York", n ...