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

Refresh choices for the user interface selection menu

I've successfully mastered the art of redefining options for Webix ui.richselect/ui.combo. The technique involves: richselect.getList().clearAll(); richselect.getList().parse(options_data) Now, I'm facing a challenge with changing options fo ...

Guide to implementing CSS3 transitions with prefixes using JavaScript

Is there a way to apply CSS styles using JavaScript when I don't have access to the CSS file? #fade div { -webkit-transition: opacity 1s; -moz-transition: opacity 1s; -o-transition: opacity 1s; -ms-transition: opacity 1s; transition: ...

Learn how to automatically fill prototype cell text labels with NSDictionary data pulled from JSON through AFNetworking

Recently delving into iOS development, I have been working on downloading JSON data using AFNetworking and storing it in a Dictionary object. Check out the code snippet below to see how this is accomplished: -(void)locationRequest { NSURL *url = [NSURL U ...

I wish for the value of one input field to always mirror the value of another input field

There is a checkbox available for selecting the billing address to be the same as the mailing address. If the checkbox is checked, both values will remain the same, even if one of them is changed. Currently, I have successfully achieved copying the mailing ...

Halt the adhesion of the Bootstrap column when it hits the div section

I have a simple bootstrap row containing two columns: <div class="row"> <div class="col-xs-7"> <p>Walking together</p> </div> <div class="col-xs-5" id="stay"> <p>Joyful journey</p> </div ...

Unexpected error in boot.ts file in Angular 2

I am currently experimenting with various folder arrangements for Angular 2. When attempting to launch a local server, I encounter the following error: Uncaught SyntaxError: Unexpected token < Evaluating http://localhost:3000/prod/app/TypeScript/bo ...

What steps can be taken to successfully import a JavaScript module without encountering a ReferenceError?

Recently, I created a Javascript export file with the following content: export const A = 1; export const B = 2; export const C = 3; As an experiment, I attempted to import this file into another Javascript document like so: import 'path/export_file. ...

Hmm, seems like there's an issue with the touchable child - it must either be native or forward setNativeProps to

Currently enrolled in a ReactNative course on Coursera, I am facing an error in a 4-year-old course: "Touchable child must either be native or forward setNativeProps to a native component." I am unsure about this error and would greatly appreciate any hel ...

Exploring the benefits of leveraging TypeScript with AWS NodeJS for improved stacktrace visibility over traditional JavaScript

I'm contemplating the idea of transitioning my existing JavaScript codebase to incorporate TypeScript in NodeJS. One aspect that I am concerned about is being able to view the stack trace in AWS CloudWatch (request log) in case an error occurs during ...

I'm experimenting with incorporating images into a card component using the map function in JavaScript. All aspects of the card are functioning properly except for the image

import React from 'react' import Card from '@material-ui/core/Card'import CardMedia from '@material-ui/core/CardMedia'; import CardContent from '@material-ui/core/CardContent'; import {makeStyles} from '@materia ...

center a horizontal line using StyledSheets in your project

After drawing a horizontal line, I noticed that it is positioned towards the left side of the screen. I am hesitant to increase its width. Are there any other methods to move it to the center? I attempted wrapping it with another view and using alignConten ...

Mastering the art of manipulating arrays with jquery

Trying to implement a dynamic search bar feature using jQuery. Here is the code snippet: Fiddle : https://jsfiddle.net/fpLf1to4/ var inputSearch = $('.searchInput').hide(); var searchArray = ['s','e','a',& ...

Setting up a connection to MongoDB on a local network using express and mongoose

As I set up a server with express and mongoose, my goal is to make it accessible on other devices within my local network. To achieve this, I configured the bind_ip variable to 0.0.0.0 in the Mongodb configuration file. const connection = mongoose .co ...

What is the best method to create random coordinates that fall outside of the circle located within a rectangular area?

Suppose the following scenario: A rectangular area with dimensions length l and breadth b A circle with a radius r The circle is positioned inside the rectangular area as depicted in the image below Check out the image here - Red areas show expected even ...

Deciphering JSON information in RAILS 3.0.6 that is provided via an HTTP POST request using the content-type application/x-www-form-urlencoded

Upon receiving an HTTP POST from a third party with content-type specified as 'application/x-www-form-urlencoded' in my RAILS 3.0.6 controller, I attempted to parse the request in two ways: Firstly, by accessing the status parameter like so: job ...

Ag-Grid is failing to display MenuTabs

I need help getting the columns menu tab to appear in Ag-Grid. It should be a simple task. I want both the general and columns tabs, similar to the demo shown here Currently, when I specify both tabs, only the general tab is displayed. If I specify just t ...

Transmit a JSON GSD Command to the Zebra Printer

Looking to communicate with Zebra printers using Python and send commands instead of just labels. According to the documentation on page 574, it shows: Below is the code snippet I am using: mysocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) ...

Initiating a animation prior to the execution of JQuery's load() function

I'm currently exploring the functionalities of JQuery's load() function and I am puzzled as to why a particular animation does not occur prior to the load request. For instance, when I include a script like this: $('#clickme').click(f ...

Aggregating multiple parameters in a D3 Treemap visualization

I have come across an interesting challenge while working on a project involving a zoomable treemap. I am currently exploring how to pass and aggregate multiple parameters within the treemap, similar to what is typically done in a zoomable treemap visualiz ...

Calculator for calculating values using JavaScript data attributes

One issue is that certain elements are canceling each other out.. The value of the element is specified in the "data-price" attribute. My code is currently not valid and does not handle it properly, ideally I would like to update the total whenever a selec ...