CodexBloom - Programming Q&A Platform

Regex Not Matching Custom File Extensions in Node.js - implementing Case Sensitivity

👀 Views: 45 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-09
regex node.js javascript JavaScript

Quick question that's been bugging me - I've looked through the documentation and I'm still confused about I've been struggling with this for a few days now and could really use some help... I'm trying to use a regular expression in my Node.js application to match filenames with certain custom extensions like `.txt`, `.md`, and `.json`. However, I'm running into issues with case sensitivity where my regex doesn't match `.TXT` or `.Md` extensions. Here's what I've tried so far: I'm using the following regex pattern: ```javascript const pattern = /\.(txt|md|json)$/; ``` I tested it with the following filenames: ```javascript const files = ['document.txt', 'notes.Md', 'data.JSON', 'image.png']; ``` I expected the regex to match `document.txt`, `notes.Md`, and `data.JSON`, but it only matches `document.txt`. To deal with case insensitivity, I tried appending the `i` flag to the regex like this: ```javascript const pattern = /\.(txt|md|json)$/i; ``` ``` But now it's matching `notes.Md` and `data.JSON`, but I'm seeing unexpected behavior where it also matches strings like `file.txt~` (the tilde is a common temporary file suffix in some editors). I want to strictly match only the specified extensions without accidentally matching temporary or backup files. How can I modify my regex to ensure it matches only the intended extensions and is case insensitive? I also want to make sure that it does not match any filenames that have additional characters after the specified extensions. What am I doing wrong? I'm using Javascript LTS in this project. I'm working with Javascript in a Docker container on Windows 10. What's the best practice here?