Contrasting the disparities between creating a new RegExp object using the RegExp constructor function and testing a regular

Trying to create a robust password rule for JavaScript using regex led to some unexpected results.

Initially, the following approach worked well:

const value = 'TTest90()';
const firstApproach = /^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2,})(?=(.*[!@#$%^&*()\-_+?.]){2,}).{8,}$/.test(value);

The variable firstApproach returned true as expected.

Next, attempting a different approach using new RegExp resulted in:

const pattern = '/^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2,})(?=(.*[!@#$%^&*()\-_+?.]){2,}).{8,}$/';
const regex = new RegExp(pattern);
const secondApproach = regex.test(value);

Surprisingly, secondApproach now evaluates to false even with the same regex pattern.

The reason behind why secondApprocach is not returning true remains unclear, and I am determined to uncover where the error lies. Thank you!

Answer №1

Remember not to include the "/" within the string when defining your pattern.

Just a friendly reminder, using /..../ in JavaScript is how you create a Regular Expression (RegExp).

For example, /word/ would be equivalent to new RegExp('word'). However, by doing new RegExp('/word/'), you're actually including an extra forward slash that should be removed.

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

Reserve a spot for a credit card in 4-digit format with VueJS

When I enter a credit card number, I want to automatically insert a space after every 4 digits. For example: 0000 0000 0000 0000 I am currently using vue js and have come across examples using jquery, but I prefer not to use jquery. Any help would be appr ...

Encountered an error trying to access property 'history' of an undefined value while using react-router v4 and create-react-app

I encountered an issue with using Link to navigate, here's the breakdown of my code: Directory structure components ----App.js ----home ----Home index.js index.js import React from 'react'; import ReactDOM from 'react-dom'; ...

Animating CSS with jQuery for a background image effect

I have the following JavaScript code : $(".linksColl a li").hover(function () { $(this).css({ "background-image" : "url(images/links/linkHover1.png)", "background-position" : "center center", ...

Testing the Limits of CSS Hover

I'm having trouble figuring out how to implement this. When hovering, a yellow square/background should appear with an offset similar to the one in the image below. I am utilizing bootstrap for this project. Any assistance or guidance would be greatl ...

Mastering the art of building a datepicker: A comprehensive guide

Looking for advice on how to create a datepicker in HTML without relying on bootstrap or pre-built JavaScript and CSS. I am interested in learning the process from the ground up and understanding how developers have designed these tools. I am specifically ...

Tips for Retrieving the Key Names of JSON Objects within a JSON Array

I'm trying to retrieve the object names "channelA" and "channelB". Here is the JSON data: [ { "channelA": { "programmes": [ { "start_utc": 1522208700, "stop_utc": 152220 ...

You can't retrieve a JSON object using Javascript

Every time I execute the javascript/php code below, I encounter an issue where I keep receiving "undefined" when trying to alert the 'userid' property of the json object. However, if I turn the json object into a string using stringify(), it corr ...

When employing the map function in React, the resulting array is always equal to the last element within

Recently delving into the world of React, I encountered an issue while trying to assign unique ids to an array of objects within a Component's state using the map function. Strangely, despite my efforts, all elements in the resulting array ended up be ...

Concealing Vimeo's controls and substituting them with a play/pause toggle button

I'm currently working on implementing the techniques demonstrated in this tutorial (), but unfortunately the code in the fiddle I put together doesn't appear to be functioning correctly. I'm at a loss as to what might be causing this issue. ...

Can you explain how the interactive notification on stackoverflow is generated when you are responding to a question and someone posts a new answer?

Have you ever been in a situation where you're writing an answer to a question, but then someone else posts their response and a popup appears notifying you of the new answer? I'm curious about how that whole process works. It seems like the answ ...

What is the best way to automatically show scrollbars when a page loads using JavaScript?

How can I make the vertical scrollbar appear as soon as the page loads using javascript? I am currently using a jquery slide toggle animation that causes the vertical scrollbar to show up because it makes the page longer. However, when the scrollbar appear ...

Solving Mixed Content Issues in JavaScript

I'm attempting to retrieve information from OMDB API, but I'm encountering an issue with mixed content images. OMDB pulls its data from IMDB, which does not allow the use of https images. Therefore, all image sources must be prefixed with http. ...

Tips for Accessing Values in a Dynamic Array in Vue.js

ArrayOrdered :[ { name :"PRODUCT 1", price :"20", amount:"10", Total 1:" ", discount : "" , Total 2:" " }, { name :"PRODUCT 2", price :"50", amount:"20", Total 1:" ", discount : "" , Total 2:" " }, { name :"PRODUCT 3", price :"15.5", amount:"10", Total ...

In order to properly set up an AutoNumeric object, it is essential to have at least one valid parameter provided

I've been working with the AutoNumeric library in my Vue js V2 application and keep encountering a specific error message in the console Issue with mounted hook: "Error: At least one valid parameter is needed to initialize an AutoNumeric object& ...

Reduce the size of JavaScript code in the browser with minification/obfuscation

I am looking for a way to minify/uglify a JavaScript snippet directly in the browser without using tools like webpack or grunt. I have tried using uglify js and other solutions, but they all seem to require the fs module which is not available on the cli ...

Employing on() for triggering a form submission

I am attempting to attach a submit event handler to a form that may not always be present in the DOM, so I am using .on(): $('body').on("form","submit", function(e){}) However, when checking Firebug, it shows: $("body").on is not a function ...

Stringification will not work on the virtual object that has been populated

Here is the object passed to the view: app.get('/view_add_requests', isLoggedIn, function (req, res) { var my_id = req.user._id; // this is the senders id & id of logged in user FriendReq.find({to_id: my_id}).populate('prof ...

res.render() Displaying Data in Frontend using Local Variables

I have a question regarding defining local variables in Express. When I use res.render(view, {variable: variable}), how can these variables be accessed on the frontend? Where are they stored? I attempted to access a variable with console.log(variable), but ...

Learn how to create an endless scrolling effect on a static webpage using only pure JavaScript

Looking to achieve an Infinite Page Scroll Effect similar to Twitter without relying on jQuery or any other library, using pure JavaScript. I'm new to JavaScript and need assistance with implementing this effect in search results displayed within a La ...

A dynamic substitute for the Supersized slideshow option

I am in the process of updating my website and the final task on my to-do list is to replace the Supersized plugin with a more suitable alternative. The website is constructed using WordPress and I am utilizing jQuery. My goal is to find a fullscreen slid ...