Regular expression that identifies any string that does not conclude with .json

Currently, I am grappling with creating a JavaScript regex for a web application that identifies anything not ending in .json. It seems like a straightforward task, but it is proving to be quite challenging.

Initially, my approach was using this regex pattern: ^.*(?!\.json$), however, it only matched the entire string. Next, I attempted ^[^\.]*(?!\.json$) which ended up matching ab in abc.json.

I have managed to come up with two separate regex patterns that accomplish the task individually, but I am determined to consolidate them into a single regex.

// Identifies anything with a dot except for those ending in .json
^.*\.(?!json$)
// Identifies anything without a dot
^[^\.]*$

To test these regex patterns, I utilize http://regex101.com/#javascript.

In my ExpressJS route definition, I implement the regexp within app.get(REGEXP, routes.index).

Answer №1

Attempt using this regular expression: /^(?!.*\.json$).*$/

/^(?!.*\.json$).*$/.test("foo.json")
Result: false
/^(?!.*\.json$).*$/.test("foo")
Result: true
/^(?!.*\.json$).*$/.test("foo.html")
Result: true

Answer №2

If you want to check the file extension, one way is to extract it using regular expressions.

Here's a regex pattern to find the file extension:

/\.[^.]*$/

You can then extract the file extension like this:

var ext = /\.[^.]*$/.exec("example.txt");

if(ext[0] === ".txt"){
    // Do something
}

Answer №3

Have you considered trying to test for "not match (.json)" instead of testing for "match (not .json)?" It might be simpler.

Answer №4

To efficiently target .json files, I suggest developing a regex expression for them. When validating the presence of .json files, consider flipping the logic with a

validation == false

This approach would streamline the process and clarify your intentions, enhancing readability for fellow developers.

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

As you scroll, the opacity gradually increases, creating a dynamic visual

Struggling to replicate a feature on a website where images gain opacity as you scroll down? Check out this site for reference: . While my current code somewhat achieves this effect, I'm having trouble figuring out how to apply a darker opacity gradua ...

InvalidType Error: The roles provided are not in the correct format, it should be a Role, Snowflake, or an Array/Collection of Roles or Snowfl

Having trouble setting up multiple select menu options on Discord.js v14. I'd like to assign more than one role to a member when multiple options are chosen in the dropdown menu. However, I'm encountering this error message: TypeError [Invalid ...

What is the best way to setup subdomains through Docker, configure nginx with a config file, and compile a React application within a container

Hey everyone, I'm currently working on a project that involves setting up a server with node/express and using react in a small node container for the deployed site. I'm routing everything through nginx for reverse proxy, but I've hit a road ...

Trigger a function upon clicking a DOM element in Vue.js

My goal is to trigger a function whenever I click on elements in the DOM that have a specific class. Despite my efforts, the functionality doesn't seem to work, and no errors are being reported. Here's the relevant code: methods: { ...

Identifying changes in data streams

I am attempting to update the value of a div when the data attribute of another div changes. This is my code: $('.language-rate').attr("data-rate-value").on('change', function () { $('.language-d').text($('.language- ...

Is it possible to dynamically insert a ng-mouseover in AngularJS using Javascript?

It seems like there is an issue with this code: var run_div = document.createElement('div'); run_div.className = 'whatever'; run_div.textContent = 'whatever'; run_div.setAttribute('ng-mouseover', 'console.log(&b ...

Creating a versatile HTTP GET method with Node.js and Express

I'm facing an issue with the code below: var getRequest=function(options){ var body=''; var req = http.get(options,function(response){ response.on('data', function(chunk) { body+=chunk; }).on('end', fun ...

What is the best way to break down a <table> into several <div> elements?

Currently, I am dealing with a vast amount of data presented in a table format with numerous rows and columns. To manage this, I have opted to enclose the table within an overflow:scroll div. However, I am seeking a solution that allows me to keep the firs ...

Utilizing and saving JSON data in JavaScript

I am currently working on developing a 2D, top-down RPG game inspired by Zelda for the web... My plan is to organize dialog in JSON format... Right now, I have the JSON data stored in an external JavaScript file called js/json.js: function getJson() { ...

The ObjectId class constructor must be called with the 'new' keyword in order to be invoked

I am currently attempting to utilize the get method in Express from a local MongoDB database. For a request /Movies/:id, it is supposed to extract the details of the movie. However, instead of functioning properly, I am encountering the following error: Ty ...

Is there a way to utilize javascript std input/output in repl.it effectively?

I created a straightforward program that calculates the factorial of a specified number, and I am interested in running it on repl.it. During its execution, I would like to interact with standard input and output through the command line. Is there a way ...

The constant response is always "I'm unsure of the solution" regardless of the existing context and apparent data

I've been exploring a project that combines LangChain, Google's Generative AI model Gemini-1.5-pro, and Neo4j to create an advanced Q&A system. This system is designed to provide answers by querying a Neo4j graph database. While my setup is ...

Is there a way for me to obtain a selection of 20 random items from this JSON data

When working with my JSON data using Myjson.slice(1, 20), I encountered a situation where I needed to extract only 20 items from a dataset that had a length of 2624. In the code snippet provided, I attempted to use the slice method but struggled to differe ...

Ways to avoid an infinite loop caused by onAuthStateChanged Firebase Authentication

I have a provider setup that initializes the authentication context from Firebase Auth. Everything is working well, but when I tried to introduce persistence by adding an observer with onAuthStateChanged, it caused an infinite loop. Despite including an u ...

Utilize Lodash to group by ID and calculate the sum in order to assign the new sum value

Is it possible to use Lodash to sort and group by a specific key (such as "id") and update the values of the elements by adding all unique values of another key (e.g. payout)? For example, can we take the array below: [ { id: 1, payout: 15, ...

Creating Swagger clients from scratch

I am working on a project that is based on npm and I am looking to add a swagger-based REST API client. My plan is to use a yaml file for the API description and generate the client during the build process. Are there any popular methods or tools for acc ...

Creating a mind map: A step-by-step guide

I'm currently developing an algorithm to create a mind map. The key focus is on organizing the nodes intelligently to prevent any overlap and ensure a visually pleasing layout. Take a look at this snapshot (from MindNode) as an example: Any suggestio ...

Using JavaScript to dynamically add items from a menu and include a delete button for the option to remove them

//I am embarking on an exciting AJAX lab where I will be experimenting with dynamic element creation and deletion. Below is a snippet of the code to get started. //Generate elements and text nodes along with a deletion button for each item in the cart fu ...

Updating JSON in JavaScript

I am striving to structure a JSON object in the following manner: {"tokenId":1,"uri":"ipfs://bafy...","minPrice":{"type":"BigNumber","hex":"0x1a"},"signature":"0 ...

Passport causing TypeError: req.session.regenerate not recognized as a valid function

Hello! I am currently enrolled in the Node with React full web stack course and I have encountered a major issue. I am unsure of why it is appearing or where it is coming from. The error displayed in my terminal is: req.session.regenerate(function(err) { ...