Pattern matching to exclude a subdirectory

I'm currently working on setting up automatic global registration. I'm encountering difficulty in finding a way to exclude a specific sub directory. Can someone provide an example of a regex pattern for excluding a particular directory? Unfortunately, I don't have any attempts to show as I am unsure where to start. I tried searching online and found some examples, but none of them seem to match the requirement of excluding only a directory.

Below is the code snippet that I am using to get the components:

const registerComponents = () => {
  const pascalCase = (name: string) => {
    return _.chain(name).camelCase().upperFirst().value()
  }

  const context = require.context('@/components', true, /\w+\.(vue)$/)
  _.forEach(context.keys(), fileName => {
    const componentConfig = context(fileName)

    const name = (fileName.split('/').pop() || '').replace(/\.\w+$/, '')
    const componentName = pascalCase(name)

    Vue.component(componentName, componentConfig.default || componentConfig)
  })
}

This is how the structure looks like. I want to exclude the folder /_exclude/

components/_exclude/file.vue
components/_exclude/file2.vue
components/_exclude/svg/globe.vue
components/some-file.vue
components/svg/cart.vue

Answer №1

This regex pattern is designed to select all files with a .vue extension, excluding those located in the _exclude/ directory:

/^\.\/(?!_exclude\/).*\.vue$/

Detailed Explanation of the regex pattern:

^\.\/

This part of the pattern matches the initial ./ in file paths obtained from require.context().

(?!_exclude\/)

Using negative lookahead, this portion ensures that _exclude/ is not included in the match.

.*

Matches any character(s). It is worth noting that using \w+ as in your original pattern would have failed on file separators in the paths.

\.vue$

Matches the file extension .vue. The parentheses around (vue) in your original pattern would have created an unnecessary capture group.

Answer №2

For your scenario, the solution is straightforward:

console.log( 'components/_exclude/file.vue'.replace(/\/_exclude\//,'/')  ); // <- RegEx
console.log( 'components/_exclude/file2.vue'.replace('/_exclude/','/') ); // <- String
console.log( 'components/_exclude/svg/globe.vue'.replace(/\/_exclude\//,'/') );
console.log( 'components/some-file.vue'.replace(/\/_exclude\//,'/') );
console.log( 'components/svg/cart.vue'.replace(/\/_exclude\//,'/') );

console.log( ' --- Or ---' );

console.log(
`components/_exclude/file.vue
components/_exclude/file2.vue
components/_exclude/svg/globe.vue
components/some-file.vue
components/svg/cart.vue`.replace(/\/_exclude\//g,'/') // <-- Using global flag (g) in case of more than one
);

We can also extract the component name using match:

console.log( 'components/_exclude/file.vue'.match(/(?!\/)[^/]*?(?=(?:\.[^/.]+?)?(?:[?#].*)?$)/)[0] );
console.log( 'components/folder/file.vue?query=notme.ext'.match(/(?!\/)[^/]*?(?=(?:\.[^/.]+?)?(?:[?#].*)?$)/)[0] );
console.log( 'components/folder.name/file.vue'.match(/(?!\/)[^/]*?(?=(?:\.[^/.]+?)?(?:[?#].*)?$)/)[0] );
console.log( 'components/folder/file.min.vue'.match(/(?!\/)[^/]*?(?=(?:\.[^/.]+?)?(?:[?#].*)?$)/)[0] );

Update

To handle the pathInfo data effectively, consider the following functions:

pathInfo function

function pathInfo(s) {
    s=s.match(/(.*?\/)?(([^/]*?)(\.[^/.]+?)?)(?:[?#].*)?$/);
    return {folders:s[1],file:s[2],filename:s[3],fileext:s[4]};
}
var sample='folder/myfolder/excludeme/another/excludeme/onemore/file.min.js?query=1';
var result=pathInfo(sample);
console.log(result);
/*
{
  "folders": "folder/myfolder/excludeme/another/excludeme/onemore/",
  "file": "file.min.js",
  "filename": "file.min",
  "fileext": ".js"
}
*/
console.log(result.folders.split('/').filter(a=>a!='excludeme').join('/')+result.file);
// folder/myfolder/another/onemore/file.min.js

pathInfo (+Folders list) function

function pathInfo(s) {
    s=s.match(/(.*?\/)?(([^/]*?)(\.[^/.]+?)?)(?:[?#].*)?$/);
    return {path:s[1],folders:s[1].split('/'),file:s[2],filename:s[3],fileext:s[4]};
}
var sample='folder/myfolder/excludeme/another/excludeme/onemore/file.min.js?query=1';
var result=pathInfo(sample);
console.log(result);
/*
{
  "path": "folder/myfolder/excludeme/another/excludeme/onemore/",
  "folders": [
    "folder",
    "myfolder",
    "excludeme",
    "another",
    "excludeme",
    "onemore",
    ""
  ],
  "file": "file.min.js",
  "filename": "file.min",
  "fileext": ".js"
}
*/
console.log(result.folders.filter(a=>a!='excludeme').join('/')+result.file);
// folder/myfolder/another/onemore/file.min.js

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

importing files from Uploadcare using ngCordova MediaFile

I am facing an issue while attempting to upload a sound file from ngCordova's $cordovaCapture service to UploadCare. The `uploadcare.fileFrom('object')` function is failing with an 'upload' error even though I have set the public k ...

The feature of window.open and pop-up blocker integrated into the $.ajax().done() function is

When my jQuery ajax call is completed, I need to open a URL in a new tab. Here's the function I created for this purpose: var openNewTab = function() { window.open('/UrlToOpen', '_blank'); win.focus(); } If I directly cal ...

Simultaneously updating pages and states with Vuex and Vue-router

I'm currently working on a single-page application that utilizes Vuex and Vue-router. Within my store, I have a large object - let's call it X - which is loaded from a database with an identifier. The Vue-router is used for navigation between th ...

Utilize ag-grid to pair key-value for efficient filtering

Is there a way to assign key-value pairs for the filter in ag-grid and display different values to the user than what is set in the filterModel? filterParams: { values: { tyt: "Toyota", frd: "Ford", prs: "Porsche", nss: " ...

Why doesn't the Vuex store update the data property of Vue components?

Within the code snippet provided, there seems to be an issue where the c2 property of the component (app.vue) does not update when the increment function updates the counter in the store using this.$store.state.counter++; I am aware that this can be resol ...

Tips for managing several Material UI Slide Components at once

Utilizing Material UI's Slide component, I have encountered an issue with my code. Upon hovering over a card, I intend for an individual slide to appear. However, the current implementation causes both slides to be displayed when hovering over any of ...

Google Analytics in Next.js Missing Page Title Configuration

I recently set up Google Analytics on my Next.js website, but I'm encountering a strange issue where the analytics are not detecting my webpages and showing as (not set). Everything else seems to be functioning properly. I've double-checked that ...

Creating a Triangular Badge in Vuetify: A Step-by-Step Guide

I've been using v-badge to create circle badges, but I'm looking to switch things up and create triangle badges like the one below. https://i.sstatic.net/8S6Cx.png Any tips on how I can achieve this triangle badge design? Thanks in advance! ...

Transferring data through Ajax, Jquery, and PHP: A seamless process

My goal is to develop an attendance button that adds +1 to the total number of people attending when clicked by the user. I am looking for a way to achieve this without having to refresh the page. Ideally, I would like to connect it to a database to upda ...

Steps to generating a dynamic fabric canvas upon opening a new window

There seems to be an issue with the code below. When I click the button next to the canvas, my intention is to have a new window open displaying the canvas in full view. However, it's not working as expected. Can someone please assist me in troublesho ...

Exciting discovery within my coding for US Number formatting!

I am currently working on formatting 10 digits to resemble a US telephone number format, such as (###) ###-####. Although my code successfully achieves this goal, it also has an unexpected issue that I'm struggling to identify. Specifically, when ente ...

Elements recognized worldwide, Typescript, and a glitch specific to Safari?

Consider a scenario where you have a select element structured like this: <select id="Stooge" name="Stooge"> <option value="0">Moe</option> <option value="1">Larry</option> <option value="2">Curly</option ...

Updating language settings on-the-fly in a Vue application does not automatically refresh the translated content displayed on the website

My Vue app is quite large, built with Vuetify, and I recently integrated vue-i18n into it. The json translation files are set up correctly, and the $t() calls work fine in my components and other .js files. However, I'm struggling to change the locale ...

Troubleshooting Bootstrap 3.0: Issues with nav-tabs not toggling

I have set up my navigation tabs using Bootstrap 3 in the following way: <ul class="nav nav-tabs pull-right projects" role="tablist" style="margin-top:20px;"> <li class="active"><a role="tab" data-toggle="tab" href="#progress">In Pr ...

What could be the reason for the peculiar data being returned by Microsoft Graph list subscriptions?

I am currently in the process of configuring webhooks to automatically update my application's database whenever a contact is modified in Outlook. I need to modify my existing subscriptions before they expire, so I decided to retrieve a list of curren ...

Troubleshooting slow/delayed performance when using manual dataItem.set() in Kendo UI Grid

I recently implemented an editable Kendo Grid with a checkbox column to toggle a boolean value, thanks to an ingenious solution offered by OnaBai. The implementation works flawlessly! The only issue I'm facing is that there seems to be a delay in cha ...

What is the process for converting primitive values in the expressions `1 + {}` and `{} + 1`?

Being a novice developer, I am struggling to comprehend why the following statements result in different outputs. Could someone please explain why JavaScript interprets these two expressions differently and produces distinct outcomes? 1 + {} // => "1[o ...

Oops: Looks like there is already a request for 'PUBLIC_requestAccounts' pending from http://localhost:3000. Just hold tight for now

There comes a moment when an unexpected error arises and fails to establish a connection with your wallet. if (window.ethereum) { console.log("11") const connect = async () => { const account = await window.ethereum.request({ ...

Troubleshooting problem in Java related to encoding with XMLHttpRequest

Currently, I am utilizing XMLHttpRequest for an ajax call to my server. Let's consider the call: http = new XMLHTTPRequest(); var url = "http://app:8080/search.action?value=ñ" http.open("GET",url,true); http.setRequestHeader("Content-type", "applica ...

Modify the size of Points of Interest in Mapbox GL JS

Is there a way to adjust the size of POIs such as schools, restaurants, and more? https://i.sstatic.net/ZPEcZ.png I am currently using Mapbox GL v2.8.2. In the documentation, I only came across information about layers, but I'm unsure if the default ...