Leverage the power of regular expressions in JavaScript for organizing and handling source files

Embarking on my coding journey with JavaScript, I have also been exploring the world of Three.js, a webgl library.

After watching tutorials and conducting experiments, I am proud to share my latest creation: .

In my code, you'll notice that the object reflects a random selection from a folder containing 13 images, out of which 6 are displayed.


    var numberOfImages = 13, images = [];
    for (var i = 1; i <= numberOfImages; i++) {
        images.push('sources/instagram/image' + i + ".jpg");
    }

    var urls = images.sort(function(){return .6 - Math.random()}).slice(0,6);
    var reflectionCube = THREE.ImageUtils.loadTextureCube( urls );
    reflectionCube.format = THREE.RGBFormat;

As I add new Instagram pictures to the folder, they are automatically included in the rotation.

However, updating the number of images in the code manually can be tedious. I'm seeking a more dynamic solution using regular expressions or other methods to adjust the code automatically based on the images uploaded.

I've come across references to regular expressions as a potential solution. Is this the best approach? Should I invest time in mastering regular expressions for this problem?

If you have any suggestions or alternative solutions, I would greatly appreciate your insights. Whether it's a simple adjustment to the code or a more complex language to learn, I want to ensure I tackle this challenge effectively.

Answer №1

Programming in any language for an extended period will require knowledge of regular expressions and their proper usage, making it beneficial to learn them.

If dealing with a client/server problem where server control is possible, a common solution involves the server scanning its file system and informing the client about the number of images needed.

If the task must be completed solely on the client side, direct file system scanning is not feasible. However, requesting incrementing file numbers and monitoring image loading success can provide insight asynchronously, though coding this process may pose challenges due to asynchronous responses.

The following is a proposed method for preloading images and identifying where successful preload stops:

function preloadImages(srcs, callback) {
    var img, imgs = [];
    var remaining = srcs.length;
    var failed = [];

    function checkDone() {
        --remaining;
        if (remaining <= 0) {
            callback(failed);
        }
    }

    for (var i = 0; i < srcs.length; i++) {
        img = new Image();
        img.onload = checkDone;
        img.onerror = img.onabort = function() {
            failed.push(this.src);
            checkDone();
        }
        img.src = srcs[i];
        imgs.push(img);
    }
}

var maxNumberOfImages = 30, images = [];
for (var i = 1; i <= maxNumberOfImages; i++) {
    images.push('sources/instagram/image' + i + ".jpg");
}

preloadImages(images, function(failed) {
    var regex = /(\d+)\.jpg$/;
    var nums = failed.map(function(item) {
        var matches = item.match(regex);
        return parseInt(matches[1], 10);
    }).sort();
    var numImages = nums[0];
    // implement code here based on the obtained information
});

Note: A regular expression is utilized to extract the image number from a URL in this process.

While achieving this without a preset limit is possible, it would involve more effort. A potential approach could be requesting images in blocks of 10 and continuing until the first failure occurs.

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

Resolving a Routing Problem with moment.js

Hi everyone, I'm new to working with express.js and backend routing. I'm encountering an error with my server code and would appreciate any insights on what might be causing it. I've already tried using res.end() with plain text, but the err ...

Leveraging JavaScript code repeatedly

Apologies if this question has been asked before, as I couldn't find it. I have an HTML table with images used as buttons: <td> <button class="trigger"> <img src="D:\Elly Research\ CO2858\Presentation\Calypso ...

Errors always occur when making POST requests in SAPUI5, leading to a 500 Server Error specifically related to OData

Currently diving into the world of SAPUI5 and OData, I am in the process of creating a basic application that showcases employee data in a table. The objective is to add a new employee to the table whose information will be stored in the SAP backend. Whil ...

An Ajax call navigates to the index.html page

Could you please assist with an issue I am facing? I have written the code below to make an ajax request to a specific link. However, instead of executing the ajax call using a POST request, the page is being redirected to index.html with the link in the ...

Optimal approach for incorporating AJAX/jQuery functionality to both append to a form and refresh a list simultaneously on a single webpage

Currently, I am developing a page that consists of a form to input data into a table, as well as a list displaying items from that table. My goal is to ensure that the newest items appear at the top of the list after the form submission. At the moment, t ...

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'; ...

Selenium WebDriver keeps crashing with a newSession error after around 70 seconds of running

Recently, a perplexing error surfaced in my previously functional project without any changes to the code. The sudden appearance of this issue may be attributed to a FireFox update or a dependency failure. To help troubleshoot the abrupt cessation, I added ...

How come the light position is not updating?

I am currently using the three.js library to create an animated cylinder: let renderer, camera, scene, light, cylinder; initialize(); animate(); function initialize() { renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); renderer ...

I encountered a problem with iteration where the results appeared perfectly fine, but upon rendering at the component level, the same field loaded with the last object instead

I am facing an issue with rendering the component level when it loads. After clicking on edit and calling the edit function, the data is properly loaded in console and all objects are shown. However, they do not render on the page level. Below is the code ...

Are the files selected by the user not displaying properly in the URL?

I'm currently working on a project using PhoneGap where I am facing an issue with uploading files and adding all file names to the parameters. The desired format is: http://www.example.com/uplaod.html?file=file1,file2,file3 To achieve this, I have a ...

What is the best way to exclude a field from a Joi schema?

I've defined a Joi schema for a User with the following rules: const userRules = Joi.object({ name: Joi.string().pattern(new RegExp('^[A-Za-zÁÉÍÓÚáéíóúãõÃÕâêôÂÊÔ ]+$')).required(), email: Joi.string().email().requ ...

Top pick for building drag-and-drop web applications: the ultimate JavaScript library

Up to this point, I've relied on jQuery UI's draggables and droppables for my projects. However, I recently came across ExtJS and other libraries that caught my interest. I am aiming to create a professional-grade plugin. Can anyone suggest the b ...

Instructions for including a sentence in an array as a single element with the split method

I have a string and I want to turn it into an array by splitting it into individual elements. For example: let str = "add 2017-04-25 2 USD Jogurt" str.split(" "); ["add", "2017-04-25", "2", "USD", ...

Encountering a RuntimeError during the integration of Angular Js in Rails with ExecJS

Currently, I'm working on integrating Angular Js into a Rails Project and I've been following the tutorial provided at . However, after completing all the steps, I encountered the following error: https://i.sstatic.net/ehYCb.png I've searc ...

Hey there, what exactly does 'TypeError: Cannot access the 'scopedFn' property of an undefined object' mean?

Having trouble implementing RadListView with Nativescript-Vue. I am attempting to utilize a v-template for the header followed by another v-template for the list itself. 1) The header does not seem to be recognized, as only the standard v-template is disp ...

While running tests on a React project, the `npm test` command is successful, but unfortunately,

I created a new react app using create-react-app and included some basic components and tests. The tests work fine when running 'npm test', but I encounter an 'Unexpected token' error when using Jest to run the tests with imported compo ...

Tips for resizing a larger image to display only a specific portion in CSS (and incorporating JS if needed)

I need to resize an image that measures 1024x1024 and is segmented into 4 quadrants: My goal is to reduce the size of this image so that quadrant 2 is 256x256 while masking out or hiding the remaining 3 quadrants, displaying only the desired section on th ...

What is the best way to connect a relative CSS stylesheet to a master page?

My Java application generates several HTML pages, organized in different directories: html_pages/ | ----> landin_page.html html_pages/details | ----> index1.html html_pages/more_details | ----> index2.html html_pages/css | ...

The hamburger menu on the responsive navbar fails to open when clicked on

Having an issue with my navbar in mobile and responsive environments. The hamburger menu shows up, but when clicked on, the links are not displayed. Below is the code that I am using, all the necessary links are included but the menu is not functioning pro ...

Conceal list items by clicking elsewhere on the page

Currently, I am facing an issue with my search user functionality. Whenever a user clicks anywhere else on the page, the list of results does not disappear unless the user manually deletes all the words they have typed. This behavior is not ideal and despi ...