obtain the image number by extracting a portion of the text

How can I extract the image number from a string using the sub-string function?

I have applied the sub-string function to the property below. It returns 3 at the end in Chrome, but it does not work properly in Mozilla.

Issue : After "-->", when I check in Chrome everything looks fine. However, in Mozilla, instead of getting 3.jpg on the third step, I get .jpg

alert("obj.back is "+obj.style.backgroundImage);-->url(http://localhost/final.21/img/img3.jpg);
    origImg = obj.style.backgroundImage.split(")")[0];
    alert('origImg is'+origImg);  -->>url(http://localhost/final.21/img/img3.jpg
    alert('after length '+origImg.substring(origImg.length-5)); -->3.jpg
    origImg = origImg.substring(origImg.length-5).split(".")[0];
    alert('origImg is'+origImg);  --> 3

Answer №1

Here's another solution for you to consider

const imageUrl = 'http://localhost/final.21/img/img3.jpg';
alert(imageUrl.slice(-9, -4));

Answer №2

After further investigation, I discovered that when using the "obj.style.backgroundImage" property, Mozilla was returning url("/final.21/img/img3.jpg");, whereas Chrome was returning url(/final.21/img/img3.jpg);. This prompted me to modify my substring approach.

Answer №3

In my opinion, a more user-friendly solution can be achieved using Regular Expressions (RegEx). The current solution may encounter issues if any changes occur (such as having a file named img33.jpg). Furthermore, I find the RegEx approach to be clearer as it accurately reflects the intended action.

let url = "http://localhost/final.21/img/img3.jpg)";
const origImg = url.match("img([0-9]+).jpg");
alert('origImg is '+origImg[1]);

Answer №4

An alternative approach using Regex

let str = "http://example.com/image/photo.jpg";
str = str.substring(str.lastIndexOf("/") + 1);
console.log(str.match(/[0-9]+/)[0]);

See it in action: http://jsfiddle.net/abc123/

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

Tips on accessing files saved in a one-to-many connection using Mongoose

I have multiple Schemas set up for Shops and Products. Each shop can have a variety of products, and I currently have 5 different shops with their own unique product listings. While I am able to save the products and find their corresponding IDs within eac ...

Error Message: TypeError - Unable to access property 'method' as it is not defined

I've just started working on a new node project and I've encountered an issue that I can't seem to figure out. :\Users\RTECH\Desktop\work\aumentedreality\modelViewerwithExpress\node_modules\express&b ...

comparing multiple values separated by commas with JavaScript

I need validation using a comma-separated value format. Within the illustration, there are two fields: "Saloon Price" (value: 10,10,10,10) and "Saloon Offer Price" (value: 11,11,11,11). The first value must be less than the second. Saloon price Value & ...

Steps to display a popup notification when a table is modified by an external process

For a project I am working on, I would like to implement a feature where a pop-up message is automatically displayed when a record in the project table is updated by another process. This means that whenever a new record is added, a pop-up message will b ...

Eliminate the white background from the modal image

I'm facing an issue with an image displayed in a modal. The image has a white background that I want to remove so only the image itself is visible. https://i.stack.imgur.com/CG9Ne.png Here's the code snippet: <div id="myModal" class ...

When working with Typescript, an error may occur related to index types even though the constant object and its

I am struggling with understanding TypeScript, specifically when it comes to a problem I encountered. Hopefully, someone can shed some light on this for me. My issue revolves around a functional component that is responsible for displaying the correct com ...

What is the preferred approach in JavaScript: having a single large file or multiple smaller files?

Having a multitude of JavaScript files loaded on a single page can result in decreased performance. My inquiry is this: Is it preferable to have individual files or combine them into one JavaScript file? If consolidating all scripts into one file is the ...

Ways to retrieve a webpage component that has multiple values within its class attribute

My dilemma lies in this HTML snippet: Within the code, there are two instances of <div class="sc-fjhmcy dbJOiq flight-information"></div>. I am trying to target these elements using their class attribute, specifically with the value ...

Update a separate React component in response to the interaction with a different React component

Currently, I am working with a react component named Interest Category that showcases an initial set of Interest categories. Another react component called CreateInterestCategoryDialog, which functions as a modal, is responsible for creating a new entity I ...

What is the best way to merge an array of objects into a single object?

Is there a way to dynamically convert object1 into object2, considering that the keys like 'apple' and 'water' inside the objects are not static? const object1 = { apple:[ {a:''}, {b:'&apos ...

Concerning Java's Map and Array functionalities

When working with Javascript, we have the ability to create statements like the one below. var f_names = { 'a' : 'Apple', 'b' : 'Banana' 'c& ...

Issue with Chrome not triggering onMouseEnter event when an element blocking the cursor disappears in React

Important Note: This issue seems to be specific to Chrome Currently, React does not trigger the onMouseEnter event when a blocking element disappears. This behavior is different from standard JavaScript events and even delegated events. Below is a simpli ...

Executing a script within an ASP.NET MVC Project

Currently, I'm in the process of developing a project in MVC that requires using AJAX to fetch XML from an external source. However, I have encountered a challenge where I am unable to directly make the AJAX call due to a XMLHttpRequest same domain po ...

Improving website speed and efficiency with asynchronous loading using AddThis

After following the instructions in the guide, I was able to trigger addthis using ajax, but it seems to only work on one specific location. For example, on the html index page 'index.php', <a href="#" class="load">click to load</a> ...

The three.js library is throwing an error because it is unable to access the 'geometry' property of an

function CreateNewSphere(x, z) { var sphereGeometry = new THREE.SphereBufferGeometry(10 * factor, 32, 32); var sphereMaterial = new THREE.MeshBasicMaterial({ color: SphereColor, wireframe: false }); var sphere = new THRE ...

The top section of the page is not properly aligned with correct bootstrap spacing and margins, leading to a

Inspiration theme: Porto (The work items on the right are aligned with the top of the viewable portion of the page) when selecting 'view all' on the left menu. Website using the Porto template: DMMBlitz (The work items on the right are NOT alig ...

JavaScript's ability to call object properties at multiple levels allows for complex data

My approach involves using mongodb in conjunction with ajax calls for data retrieval. However, I have encountered an issue where the properties needed to generate HTML from JavaScript objects are sometimes missing. Consider this ajax call: $.ajax({ ...

The passing of query string parameters from JavaScript to a PHP processing script is ineffective

I am looking to dynamically populate a jQWidgets listbox control on my webpage with data retrieved from a MySQL database table once the page has finished loading and rendering. PARTIAL SOLUTION: You can find a solution here. NEW PROBLEM: I have created a ...

The header in the fetch() function is displaying as application/x-www-form-urlencoded rather than the expected application/json

Update #2: The issue has been resolved, you can find the solution in my own answer (which I am unable to accept at this time). I have a React application running on Heroku with a node.js backend via Express. In the frontend, I am attempting to send a POST ...

Adding a unique component to a Spring Boot application with Thymeleaf integration

My navigation bar includes a list with a dropdown feature. When the user clicks on the dropdown entry, I want to display a snippet of another HTML page within the project. The navigation bar HTML code is as follows: <div th:fragment="navbar"& ...