Utilizing regular expressions on a URI parameter in JavaScript

I implemented an ajax function that retrieves three images (PORTRAIT, SQUARE, and LANDSCAPE) from a JSON response:

$.ajax({
            url: link,
            method: 'GET',
            headers: {
                "Authorization": authToken
            },
        }).then(function (response) {
            var data = response;
            $("#imageid").css("border-color", "#ccc");
            $(".search-results").empty();
            for (var prop in data.entity.entries) {
                if (data.entity.entries.hasOwnProperty(prop)) {

                        var imgURL = data.entity.entries[prop].uri + "&" + imageCacheBust;
                        $(".search-results").append($("<li><a href='" + imgURL + "' target='_blank'><div class='thumbnail'><img width='30' height='30' src='" + imgURL + "' target='_blank'/></img><div class='caption'><p>" + data.entity.entries[prop].orientation + "</p></div></a></li>"));
                    }
                }

        }).fail(function (errorData) {
            $(".search-results").empty();
            $(".search-results").append("<p class='alert alert-danger'>Invalid ID</p>");
            $("#imageid").css("border-color", "red");
        });

The LANDSCAPE and SQUARE images come back as URIs structured like this:

http://xx.domain.com/api/v2/img/55527b6060b27c50d1def7b6?location=LANDSCAPE&1
http://xx.domain.com/api/v2/img/55527b6060b27c50d1def7b6?location=SQUARE&1

However, the PORTRAIT image URI appears as:

http://xx.domain.com/api/v2/img/5550fdfe60b27c50d1def72d&43

I attempted to use a regex pattern to remove everything following the LAST occurrence of d at the end of the portrait URL to avoid caching issues. Unfortunately, this manipulation is not functioning correctly, resulting in the image failing to display.

Answer №1

Have you considered using the split method instead? If I understand your problem correctly, you could potentially replace the following:

var regex = /[^d\/]*$/;
var imageURI = regex.exec(obj.entity.entries[property].uri);

. . . with this . . .

var imageURI = obj.entity.entries[property].uri.split("&")[0];

This would split the value of uri into an array containing "" and "43", allowing you to reference the desired part by using the index 0 (which appears to be what you are seeking).

Answer №3

By incorporating elements of @Ankit's suggestion, I was able to come up with a solution. In this revised code snippet, I included the images in both the if and else statements, along with changing the & in the first statement to ?:

$.ajax({
        url: url,
        method: 'GET',
        headers: {
            "Authorization": bearerToken
        },
    }).then(function (response) {
        var obj = response;
        $("#imageid").css("border-color", "#ccc");
        $(".search-results").empty();
        for (var property in obj.entity.entries) {
            if (obj.entity.entries.hasOwnProperty(property)) {
                if(obj.entity.entries[property].orientation == 'PORTRAIT'){
                    var imageURI = obj.entity.entries[property].uri + "?" + imageCacheBust;
                    $(".search-results").append($("<li><a href='" + imageURI + "' target='_blank'><div class='thumbnail'><img width='30' height='30' src='" + imageURI + "' target='_blank'/></img><div class='caption'><p>" + obj.entity.entries[property].orientation + "</p></div></a></li>"));
                }else {
                    var imageURI = obj.entity.entries[property].uri + "&" + imageCacheBust;
                    $(".search-results").append($("<li><a href='" + imageURI + "' target='_blank'><div class='thumbnail'><img width='30' height='30' src='" + imageURI + "' target='_blank'/></img><div class='caption'><p>" + obj.entity.entries[property].orientation + "</p></div></a></li>"));
                }
            }
        }
    }).fail(function (data) {
        $(".search-results").empty();
        $(".search-results").append("<p class='alert alert-danger'>Invalid ID</p>");
        $("#imageid").css("border-color", "red");
    });

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 the height is expanded, the background color gradually infiltrates the body of the page

I am currently working on an angular application that utilizes angular-pdf. The controller and view function perfectly, and the PDF is displayed correctly, except for one issue. The height of the PDF exceeds the min-height of the module, causing it to expa ...

Transforming AJAX into jQuery

How can I rewrite the following code using only the jQuery library? <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> function do_it(value) { var url = "test.p ...

Instantiate a fresh Date object in JavaScript by passing in my specific parameter

Check out this code snippet: $(function () { var timestamp = 1443563590; //Tue, 29 Sep 2015 21:53:10 GMT var today2 = moment.unix(timestamp).tz('America/New_York').toString(); alert(today2); //var dateinNewYork = new Date(wh ...

Kurento's WebRTC feature is currently experiencing difficulties with recording functionality

Currently, I am attempting to capture video using the Kurento Media Server with nodejs. Following the hello-world example provided here, I connected a recorderEndpoint to the webrtcEndpoint and successfully got everything up and running. However, on the se ...

Utilizing Sequelize validation through condition objects

const db = require("../models"); const Meet = db.meet; checkDuplicateTime = (req, res, next) => { Meet.findAll({ where: { tanggal: req.body.date, waktu: req.body.time } }).then(time => { ...

The Angular Google Maps Module fails to initialize

After updating angular-google-maps to version 2.0.1 via bower and adding the required dependencies (bluebird, jquery, loadash), I noticed that my app works fine when I comment out google-maps. This suggests that the issue lies with angular-google-maps. He ...

Incorporating CSS into React.js applications

I am currently working on a project using MERN.io. In my project, I am utilizing the React.js component Dropdown. However, the Dropdown component does not come with its own style and CSS, resulting in no styling at all. ... import Dropdown from 'rea ...

Ways to move down only one level of an element's children, excluding sub-levels

When implementing this code snippet: jQuery: $(this).next().slideDown() with a selector :$(this).next() HTML: <li class="sub-menu two-level-collapse"> <a href="javascript:void(0);" class="two-level-collapse parent">< ...

Oops! There seems to be an issue with trying to access the 'map' property of undefined within the render method

While working on my project, I encountered an issue with a table from react material ui. The problem arises when attempting to populate the table with data from the state, resulting in an error message stating "cannot read property 'map' of undef ...

What is the process for retrieving API information with jQuery's AJAX functionality?

In this code, I am working with a standard dropdown menu containing city names. However, my goal is to use jQuery to retrieve JSON data in an alert box when the selected city is changed - unfortunately, this functionality is not currently functioning. I ...

Sorting rows dynamically with jQuery Tablesorter

I've been struggling to find a solution for my specific issue. I need to have a static row in a large table that will not sort or move, allowing for repeated headers. Can anyone offer assistance with this? $("#dataTable").tablesorter({ ...

The Invalid_grant OAuth2 error occurs when attempting to access the Google Drive API using

SOLVED! The issue was resolved by correcting the time on my Linux Server. Google's server was blocking access due to incorrect time settings. I used the following command on my Server to synchronize the time: ntpdate 0.europe.pool.ntp.org Original P ...

Solution for repairing the display location button on Android within a React Native Map

I am facing an issue with the Location Button in my React Native Maps app. When the app is opened for the first time and the map is rendered, the button disappears. However, if I close the app but leave it running in the background, upon reopening the app, ...

Creating a Show/Hide toggle feature in AngularJS using NG-Repeat

I'm facing an issue with my code where I have a list of items that should only open one item at a time when clicked. However, currently, all items are opening on click and closing on the second click. Can anyone help me identify the problem in my code ...

The screen suddenly turns black just moments after starting the video

Currently, I am utilizing the Youtube JavaScript API to embed videos on my webpage and control a playlist. However, I keep encountering an error where the video turns black right after loading the title, play icon, and loading icon. Initially, it seems lik ...

Is there a way to convert an array into an object where the first value in the array becomes the name and the properties are an array of the remaining values within subarrays?

Looking to efficiently group elements of a multidimensional array with an unknown list, and transform it into an object while removing duplicate values in the first element of each subarray: For instance, here's the initial array: const arr = [[a, 1 ...

Issue with React Google Maps Api: Error occurs while trying to access undefined properties for reading 'emit'

I'm trying to integrate a map using the google-map-react API, but I keep encountering the following error: google_map.js:428 Uncaught TypeError: Cannot read properties of undefined (reading 'emit') at o.r.componentDidUpdate (google_map.js: ...

Trouble Arising from Making a POST Request to Spotify's API

I am currently developing a web application that allows users to search the Spotify Library, add songs to playlists, and then save those playlists to their Spotify Accounts. Almost everything is functioning correctly except for the saving of playlists thro ...

Remove webpack functions from the bundle

After following a comprehensive tutorial on bundling files with webpack and some additional online research, I successfully created a configuration file that organizes the modules in my library into the specified structure: dist/node/weather.min.js dist/we ...

results vary when using both a while loop and callback

I'm having an issue with my while loop when filtering data from mongodb. Even though I should be getting three entries logged to the console, only one entry is making it to the callback function. Can anyone explain why this is happening? while(i--) { ...