Extracting the name of the file from the image's web address

I have created a simple Chrome extension for personal use and sharing with friends. I am dealing with URLs that have various formats, such as:

i.imgur.com/abcd123.png or imgur.com/a2b3c78 or even i.imgur.com/herp321.png?1

All I need from these URLs are the 7-character codes before the file extensions. For example, abcd123, a2b3c78, and herp321.

I have tried using .replace but it doesn't handle exceptions like the third example. I also attempted to use regex, but couldn't get it to work properly. The only constant part of the URL is the following format, with the code represented as x:

imgur.com/xxxxxxxx

The beginning and end of the URL may vary, but the above format remains consistent. Is there a way to extract just the alphanumeric filename from the examples provided, regardless of what comes before the URL or any additional modifications/extensions?

Answer №1

imgurLink=str.match(/imgur.com\/(.{7})/);
//The result can be found in imgurLink[1]

Answer №2

Here's a straightforward solution:

 let imageLink = 'i.imgur.com/derp456.png?1'
 let pattern = /imgur\.com\/(\w{7})/;
 
 console.log(imageLink.match(pattern)[1]);

Answer №3

You might want to consider using the following regex pattern in your code:

/.+\/([a-z0-9]+).+/

If you are working in JavaScript, you can implement it like this:

var imageUrl = 'i.imgur.com/dsf8635235.png?sdgdsgdsg'
  , results = imageUrl.match( /.+\/([a-z0-9]+).+/ );

console.log( results[ 1 ] ); // dsf8635235

There are several variations you could try as well:

console.log( 'imgur.com/dsf8635235'.match( /.+\/([a-z0-9]+).+/ )[ 1 ] ); // dsf8635235
console.log( 'i.imgur.com/dsf8635235'.match( /.+\/([a-z0-9]+).+/ )[ 1 ] ); // dsf8635235
console.log( 'imgur.com/dsf8635235?1'.match( /.+\/([a-z0-9]+).+/ )[ 1 ] ); // dsf8635235

Feel free to experiment with these patterns and see what works best for your specific scenario.

Answer №4

To implement this functionality, you can utilize the match function along with a regular expression.

UPDATE:

Here's a possible solution:

var links = ["i.imgur.com/abcd123.png", "imgur.com/a2b3c78", "i.imgur.com/herp321.png?1"];
var pattern =  /\/(.{7})/;

for(i=0;i<links.length;i++) {
  pattern.exec(links[i]);
  console.log(RegExp.$1);
}

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

Cordova Geolocation now displaying incorrect latitude and longitude values as NAN

Recently starting out with javascript and Cordova, I decided to develop a basic GPS app in Visual Studio 2015. The goal was simple: get my current position by clicking on the "CURRENT POSITION" button. Testing it in Firefox yielded positive results. Howev ...

Attempting to showcase the data stored within MongoDB documents on my website's user interface

I am facing difficulties in showing the data stored in my database on the front end of my grocery list app, which is built using the MERN stack. I have a form that successfully sends data to MongoDB and saves it upon submission. In order to retrieve the d ...

sending a POST request with fetch

When it comes to making AJAX requests, I used to rely on jQuery in the past. However, with the rise of React, there is no longer a need to include the entire jQuery library for this purpose. Instead, it is recommended to use JavaScript's built-in fetc ...

Slicknav is failing to appear on the screen, although it is being

After spending hours trying to implement a slicknav menu into my school project, I'm stuck and seeking guidance. Despite having some coding experience, I can't seem to find the solution to my problem. Any help, insight, or tips on fixing or impro ...

Error: The function callback.apply is not a valid function (Node.js and Mongodb)

Encountered an error when adding the line "{ upsert: true }": Error message: TypeError: callback.apply is not a function // Accessing routes that end in /users/competitorAnalysisTextData // ---------------------------------------------------- router . ...

Obtaining the correct information from an array using Ionic's Angular framework

I am currently working with an array of data that contains arrays within each item. I have been able to display the data as needed, except for the IDs. Approach Show arrays within the array Retrieve the IDs of the arrays (excluding the IDs inside the ar ...

Configuring Proxy Settings for WebpackDevServer

I need assistance setting up a proxy using WebpackDevServer in my React/Node chrome extension. Currently, my server is running on localhost:4000, and the React frontend is on localhost:5000. When trying to access the route /api/user/ticket using Axios, I ...

SweetAlert html is not recognizing ng-app, but it functions correctly within the html body

When inserting a bootstrap table inside a SweetAlert, I encountered an issue where using ng-app or ng-repeat to populate data inside the table's rows did not call ng-app. However, when populating the table outside of the SweetAlert in the body, ng-app ...

Using the IE method getelementbyid to target an object within the document

Is there a way to use getElementById to access an object that already exists in the document? I am specifically trying to target the element "test" which is nested within parentDiv1. While this code works in Firefox, it's not functioning properly ...

What causes Angular2 to detect both reference changes and primitive changes even when the OnPush flag is enabled?

Take a look at this code snippet import {Component, OnInit, Input, OnChanges, DoCheck, ChangeDetectionStrategy} from 'angular2/core' @Component({ selector: 'child1', template: ` <div>reference change for entire object: { ...

What is the best way to transfer data entered into a textbox through an onclick Alert event into a database?

UI https://i.stack.imgur.com/c2cqo.png Here is the PHP code I have been struggling with. It is meant to save input data into a database, but I can't seem to get it right: if (isset($_POST['rjctrsn-data']) && !empty($_POST['rjc ...

Can anyone provide guidance on locating the parent of a pseudo element with Selenium WebDriver?

Is there a way to retrieve the parent web element of a pseudo element (if we can call it the parent) using JavaScript? I know that Selenium's methods for searching for web elements are not suitable for pseudo elements, but JavaScript does allow manipu ...

React - Error: Unable to access the 'props' property because it is undefined

I am working on implementing a click event to delete an item from my list, but I keep encountering the error message "TypeError: Cannot read property 'props' of undefined" whenever I click on it. Although I am striving to follow ES6 standards as ...

Incorporate VLC player into a webpage without any visible control options

Is there a way to embed a flash video in a webpage without showing any controls? I managed to embed a flash video using VLC with the following code: <embed src="img/Wildlife.wmv" height="480" width="640"> However, I want the video to play without ...

Retrieving and securely storing information using fetch() on authenticated REST services

Currently, I have successfully set up a React application that communicates with a REST backend which is built using Python and Flask. The specific functionality I have achieved involves downloading data from a database and saving it as a CSV file through ...

Tips for maintaining focus while tabbing in a contenteditable field?

Why does the table lose focus every time I press tab instead of inserting a white space? How can I change this so that pressing tab just inserts a regular tab space? ...

The route param is throwing a "Cannot read property 'name' of undefined" error, indicating that the property

Currently, I am enrolled in an ExpressJS course on TUTS+ From the video tutorial, I have implemented the following code snippet (excerpt from video): var express = require('express'), app = express(); app.get('/name/:name', funct ...

Iterating through elements within a Div will retrieve the initial element exclusively

Is there a way to loop through all elements within the MainDiv Div in order to retrieve their values? Currently, I am only able to retrieve the value of the first element. <div id="MainDiv"> <input type="text" id="MyText"value="Text1" /> ...

The struggle between Node.js 404 errors and Angular's URL refresh issue

I am currently developing a Node.js and AngularJS application. I encountered an issue where a page loads successfully when the URL is entered, but then I added a script to redirect to a 404 error page. Now, only one of the criteria works at a time - either ...

Steps for retrieving the identifier of a duplicated element

I've copied an element and changed their IDs, but I'm having trouble fetching the IDs of the cloned elements in jQuery. Can someone assist me with this issue? The HTML view source code is provided below: <table id="dataTable" borde ...