When the regex.test function is not functioning correctly in a Vue.js JavaScript router, issues may arise

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// ...

const allowedToAnonymous = [
  /^\/login$/g,
  /^\/signup$/g,
  /^\/home$/g,
  /^\/emailconfirm\/[0-9a-zA-Z]{8}$/g,
  /^\/serviceGuide$/g,
  /^\/$/g
];

router.beforeEach((to, from) => {
  for (var regex of allowedToAnonymous) {
    console.log(regex);
    console.log(to.path);
    if (regex.test(to.path)) {
      console.log('return');
      return;
    } else {
      console.log(regex.test(to.path));
      console.log('do not return');
    }
  }

  const checkLogin = stores.getters['userStore/checkLogin'];
  if (!checkLogin) return '/login';
});

I implemented this code in my Vue.js project. It directs users to the login page if certain regular expressions do not match the current path and they are not logged in. All console.log statements are for debugging purposes. When testing in a web browser, I observed the following behavior:

/^\/login$/g
/serviceGuide
false
do not return
/^\/signup$/g
/serviceGuide
false
do not return
/^\/home$/g
/serviceGuide
false
do not return
/^\/emailconfirm\/[0-9a-zA-Z]{8}$/g
/serviceGuide
false
do not return
/^\/serviceGuide$/g
/serviceGuide
true
do not return
/^\/$/g
/serviceGuide
false
do not return
/^\/login$/g
/login
return

Pay attention to the output near /^\/serviceGuide$/g. Even when regex.test returns true, it seems to follow the do not return path. This inconsistency occurs after browsing the website multiple times, typically 2 to 4 instances.

What could be causing this issue and how can it be resolved?

Answer №1

Inconsistent behavior may occur if regexes are saved between multiple navigations. Consider the following example:

let regex = /^\/serviceGuide$/g
console.log(regex.test('/serviceGuide')); // true
console.log(regex.test('/serviceGuide')); // false
console.log(regex.test('/serviceGuide')); // true
console.log(regex.test('/serviceGuide')); // false
console.log(regex.test('/serviceGuide')); // true

The issue here is caused by the /g flag in the regex - it searches for subsequent matches after the first one. Removing this flag will resolve the problem and allow it to match from the beginning.

The observed behavior occurs because you enter the function after a successful match. As a result, the first regex.test call inside the function returns false, followed by a true response.

To summarize: eliminate the /g flag.

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

Firestore implementing batching for realtime updates with the onSnapshot 'IN' condition

Summary I'm currently working on developing a Chat List feature similar to those found in major social networks. However, I'm facing challenges with managing state in React Native due to a common issue with Firestore involving the use of onSnaps ...

Global variable in Npm CLI

I'm working on a CLI tool that heavily relies on storing a unique identifier (uid). I attempted to use fs to store the uid; however, the file was created in the directory where the command was executed. #!/usr/bin/env node const program = require("co ...

Adjust the size of an event in the Angular Full Calendar with Chronofy, while utilizing constraints to control the drag and drop functionality

I'm currently in the process of developing an availability calendar for scheduling meetings during open times. If a time slot is unavailable, users should not be able to place an event there. While I have successfully implemented this feature, I am ...

Determine if a webpage forwards to a new link with the help of phantomjs, flagging any issues exclusively for designated websites

As a beginner in frontend development, I have a question that may seem simple. Please be patient with me. var page = require('webpage').create(), system = require('system'); if (system.args.length === 1) { console.log('Usage: ...

Basic library using babel, TypeScript, and webpack - Error: (...) is not a recognized function; within Object.<anonymous>

Recently, I encountered a strange issue while trying to bundle a simple function using babel, typescript, and webpack. You can find the example that is not working at this link. To test it, simply download the code, run npm/yarn install, npm/yarn run buil ...

The function, stored as state within a context provider, is experiencing only one update

I am facing an issue with my Next.js and Typescript setup, but I believe the problem is more general and related to React. Despite extensive research on Stack Overflow, I have not come across a similar problem. To provide some context: I have a <Grid&g ...

The navigation bar initially fills the width of the screen, but does not adjust to match the width of the table when scrolling

I've spent the last 2 hours playing around with CSS, using width:100% and width:100vw, but nothing seems to be working. Currently, the navigation bar fits perfectly across the screen on desktop browsers, so there doesn't seem to be an issue ther ...

What is the best way to manage the login notification?

Is there a way to close the alert or input the UserId and password and then click on Login? Here is the code for the alert This is how the alert appears I could use some assistance in managing this alert ...

Instructions for developing an HTML element slider using mouse dragging

I've come across plenty of slider plugins that either only allow clicking to view the next image, or if they do support mouse drag or touch capabilities, they are limited to images. Does anyone know of a plugin or method to create a mouse drag slider ...

Browser encountering HTTP response that has been shorted extensively

When making an HTTP post request using axios, I am encountering an issue where the body of the response is a large 4MB string. axios({ method: 'POST', url: url, data: data, headers : headers, }) .then(function (response) { co ...

Tracker.autorun subscription triggers repeated firing of publish callback

Working on a ReactJS and Meteor project, I encountered an unexpected behavior that I would like to discuss here: Within the code, there is a block with Tracker.autorun containing a call to Meteor.subscribe. On the server side, there is a corresponding Met ...

Instructions for removing the status bar from the configuration file

Struggling to remove the status bar that's covering my header in my Phonegap-wrapped HTML5 mobile app. I've tried adding preferences to the config.xml file, but still no luck. Here's what I added: <preference name="fullscreen" value="tr ...

What is the best way to show content depending on the selected menu using Vuetify?

Here is the reference I used: https://vuetifyjs.com/en/getting-started/quick-start To set up my project, I executed the following commands: vue create my-app, vue add vuetify, and npm run serve. This is what my App.vue looks like: <template> < ...

Consolidate information from various APIs into one centralized location

I am curious to know how one can consolidate data from multiple APIs into a single API. My goal is to retrieve the results from all four res.data endpoints and display them at /coingeckotest address. Even though I am able to see the desired result in the ...

Issue with JQuery slide toggle preventing screen from scrolling down

On my website, I have a div classed as .slidingDiv that is hidden until the anchor .show_hide is clicked, causing it to slide down. This feature works perfectly when the .slidingDiv is the only content on the page. However, if there is other content above ...

What could be causing my v-select to be rendered multiple times?

I am currently utilizing vuex and vuetify for my project. I want to create a dropdown list that displays items fetched from my server in the form of a Json object. These objects are returned as an array from my store, which I access using a getter in my co ...

Issue with Angular custom directive failing to set value even after promise resolution

I created a custom directive that works well when the user enters a value. However, I'm facing an issue where the input field is not being rendered when the form is loaded. Below is my directive code: var cuitModule = angular.module('cuitModu ...

Ways to retrieve information from a JSON using Regular Expression

I'm struggling with regular expressions and can't seem to find a solution to my problem. The JSON response from my service looks like this: "{\"Version\":14,\"Collections\":[{\"Id\" ...

Using a PHP variable within a JavaScript function to incorporate its value into a select field, ultimately generating a response using JavaScript

As I work on developing a shopping cart, I have successfully stored the total value of the items in the cart in a PHP variable named $total. I attempted to transfer this value into a JavaScript variable labeled Shipping fee. Subsequently, I created a form ...

What is the method for organizing a table based on name?

As a beginner in ReactJS, I'm currently working on a project that requires me to sort my list of pokemons by name. I've implemented the Material-UI Table for this purpose, but unfortunately, I'm facing issues with the ordering. You can take ...