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

Exploring the functionality of the PageIndicator for Wearable Technology

Exploring the Page Indicator within a Tizen Wearable Application for Gear S3 Frontier has been an interesting journey. Despite successful implementation with text content, adding controls to each section or incorporating background images has proven challe ...

Guide to vertically centering Font Awesome icons inside a circular div

Is there a way to perfectly center align font awesome icons vertically? I have tried using the line-height property when text is present, and even setting the line-height equal to the height of the div. Attempts with display:inline-block and vertical-alig ...

Angular2 bootstrapping of multiple components

My query pertains to the following issue raised on Stack Overflow: Error when bootstrapping multiple angular2 modules In my index.html, I have included the code snippet below: <app-header>Loading header...</app-header> <app-root>L ...

<ol><li>Arranges elements in a peculiar way if the image is aligned to the left</li></ol>

Explore this comprehensive presentation on combining PDFs online. In this blog post, I have encountered two instances of <ol><li> formatting. The first one is styled properly using the following CSS: .post_content ul, .post_content ol ...

Utilizing a foreach loop to control the behavior of two distinct radio buttons as a unified

Can someone help me with a code containing a 5 star rating system (radio button) for two different questions? The issue is that the ratings for each question are linked, so when I make a selection in one question, it clears the selection in the other. It& ...

Having issues with Firefox rendering JavaScript and CSS correctly

I'm trying to figure out if it's the row class from Bootstrap that's causing issues, or if there's a problem with my JS/CSS not loading properly in Firefox. It seems to be working fine in Chrome and Safari. Any ideas on what could be go ...

Running of code in <script> tag

At what point does the code inside script tags start executing? Does it happen in order? <html> <head> <title>Canvas tutorial</title> <script type="text/javascript"> function draw(){ var canvas = document.getElementById ...

Attributes for 'v-bind' directives must have a value specified

Struggling to implement a tree structure in vue.js and encountering an issue with element props. Any assistance would be greatly appreciated. I've attempted using :content="{{tempCont}}" as well as content="{{tempCont}}", but neither approach proved ...

Modifying HTML content from within chrome.tabs.onUpdated

I am currently developing my very first Chrome Extension. Everything is working smoothly, except for one specific aspect. In my manifest.json file, I have included the background.js: "content_scripts": [ { "matches": ["http://*/*","https://*/*"], "c ...

I am currently exploring React Router, but I am struggling to grasp this particular behavior

My Express server serves the Create-React-App build. When I access http://localhost:8000/ while the server is listening, my page loads correctly. However, if I reload the page or navigate directly to it from the navigation bar, instead of seeing the UI, pl ...

Utilizing grease/tampermonkey (or any other browser extension) to filter out specific characters within webpage elements

Forgive me if my language is not accurate, as I am still learning about programming. The forum that I visit has cluttered the page with unnecessary and glitchy images and text for a promotion. This has made the forum difficult to navigate. I was successful ...

Icon appearing outside the button instead of inside

Here's a button I'm working with: <button class="glyphicon glyphicon-option-horizontal" (click)="myFuncion()"></button> Recently, I updated my bootstrap library from version 3 to 4.2.1 and now the icon is no longer visible. I' ...

The value property of the input element is returning as undefined

The input value entered is always returning undefined. Despite trying various solutions found in similar questions, my jQuery code continues to return undefined. jQuery: $( document ).ready(function() { $('#Input').keypress( function(e ...

Importing libraries in TypeScript and JavaScript are not done in the same manner

As I create my own library, I aim for it to be compatible with both javascript and typescript. tsconfig.json { "compilerOptions": { "target": "es2017", "module": "commonjs", &qu ...

What is the best way to find the difference between two time moments using Moment

Hello everyone, I could really use some assistance with Moment.js. I have two input fields, one labeled Start and the other labeled Stop. start = moment().format('LT'); // This works when I click on the play button stop = moment().format(' ...

Rect cannot be resized using mouse events

I am currently working on resizing the rectangle inside the SVG using mouse events. To achieve this, I have created another circle shape at the right bottom edge of the rectangle and implemented resize events on that shape. However, I'm facing an issu ...

What is the correct way to incorporate scrollIntoView() using jQuery?

I'm trying to implement a jQuery function that will enable the last reply to scroll into view. This is my current code: function displayLastReply(replies){ replies.each(function() { if($(this).index() < nIniRep || afterReply){ $( ...

Within a <div> element, there is a <span> element with a border and a specific line height. The

Can anyone explain why the border of the span is positioned next to the top? When I remove the display property for the span, it seems to work fine. Thank you. div { height: 80px; border: 1px solid green; line-height: 80px } .inner-span { heigh ...

Creating dynamic JSON endpoints using JSP with Spring MVC

When working with JSON in my webapp, I have successfully passed a variable wordId to the Spring-mvc Controller using a static URL. However, I am unsure of the best practice for dealing with dynamic or parametric URLs. Controller Section: @RequestMapping( ...

How to Send a Multi-part Message Using AT Commands and PDU Mode in Node.js

I am trying to send a multipart message using AT commands. Single parts work fine, as do special characters. However, when the message exceeds 160 characters, it shows as sent but nothing is received. const async sendSMS(msisdn, message) { message += ...