Using Javascript regex to parse out URLs and dimensions from srcset attribute strings

The main focus of this question is to extract a URL along with its dimensions from an html attribute string called srcset. The specific criteria are as follows:

  • URL must start with either http or https
  • URL may contain a comma ,
  • URL should not have any spaces
  • Dimensions consist of digits followed by either x or w, but they don't necessarily need to be followed by those characters.

Given these parameters, the ideal method for matching would involve locating the http/https part and continuing until a space is encountered. Then, match the sequence of digits immediately followed by a w or x, optionally followed by a comma. The end of the match will be signaled by a subsequent space.

A typical example would look something like https://url.com 650w or https://url.com 650 or https://url.com 650x. Keep in mind that there is no strict standard format here.

Below is my attempted regex pattern along with a Regex101 demo link. The issue with this regex is that it doesn't group correctly:

(https?:\/\/(?:.*(?:\s+\d+[wx])(?:,\s*)?)+)

Here's a sample string to parse:

[Sample URL Strings Here]

The expected output should be:

[Extracted URLs and Dimensions Here]

Answer №1

To find the result of the sample text based on the question with 4 points, you can utilize the following regular expression:

https?:\/\/\S* \d+[xw]?(?=,|$)

This pattern will match:

  • https?:\/\/ - Matches the http and https protocols
  • \S* - Matches any combination of non-whitespace characters (which may include a comma) followed by a space
  • \d+[xw]? - Matches one or more digits followed by an optional 'x' or 'w'
  • (?=,|$) - Positive lookahead to check for either a comma or end of string

See the regex in action here

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

Aggregate the values in each position across various arrays and merge them into distinct arrays

I'm facing an issue that I can't seem to solve on my own. Imagine we have several arrays: [1,2,3] [1,2,3] [11,12,13] How do I go about extracting all the values at each index from these multiple arrays and combining them into separate arrays? T ...

Ensuring that an md-radio-group is a required field in Angular Material

Currently, I am working on a project using Angular Material where I need to enforce a required radio group. This means that the user must select a radio button before being able to submit the form. The form should be considered invalid if no radio button i ...

Guide to swapping out the variables "labels" in JavaScript

Here is the object structure: { 'File_12345.ZLM': { MeterID_12345: { BASIC_INFO: [Object] } } } { 'File_678910.ZLM': { MeterID_678910: { BASIC_INFO: [Object], } } } ======================== ...

What is the best way to add a SOTag textbox to an ASP.NET website?

Is there a way to integrate the SOTag textbox into an ASP.NET website? I found this link that provides information about the SOTag textbox. An example in PHP is shown below: <!doctype html> <html> <head> <meta charset="utf-8" ...

Using jQuery to include a sub-object in the "data" object for each AJAX request made on the webpage

Is there a way to enhance the functionality of jQuery.ajax by including a static sub-data object in every ajax request automatically? For instance, for an ajax request like this: jQuery.ajax({ url: 'request_file.php', data: { da ...

Utilize the ConditionExpression to update the status only when the current status is not equal to 'FINISH'

I'm struggling to create a ConditionExpression that will only update the status in my DynamoDB table called item. Here's what I have so far: dynamo.update({ TableName, Key, UpdateExpression: 'SET #status = :status', Exp ...

Transform JSON information into views that are strongly typed

I'm trying to convert JSON data into a model by serializing it with a class. However, I encounter an error when attempting to deserialize the data. Here is my JSON data: [{"Name":"Group1","Fields":[{"Field":"EmployeeSCP.Salary","Operator":"lt","Valu ...

Vanilla.js with Vue does not support the onclick event functionality

Currently, I am facing the need to utilize vanilla.js in my application due to the presence of html entities retrieved from the database that require special treatment. Since the babel compilation process has already concluded, I am resorting to manipula ...

Selecting a new image to use as the background on a website by utilizing

While exploring JavaScript, I successfully altered the background color: <script> function changeColor(id,color) { id.style.backgroundColor=color; } </script> <div id="container"> <p> Select a Color to ...

How can you compare array values in Vuejs while iterating through them?

WelcomeWorld.vue <template> <div> <div v-for="box in boxes" :key="box.sname"> <BaseAccordian> <template v-slot:title>{{ box.sname }}</template> <temp ...

Retrieve information from table1 where the value of id1 is equal to the value of

I am seeking assistance with a script, example here There are three tables: networks network_id network_name status offers offer_id offer_name onetwork_id status list_ip network offer In the index page at IP Address Detai ...

Utilize an A-frame conditional statement to check a variable and dynamically display various glTF models depending on its value

Is it possible to use JavaScript and A-frame () to create a scenario like this? I want to have an onload function named load() that will evaluate the value of variable x. If x is equal to one, I want the gltf with the ID of 1 to be visible while hiding th ...

Trouble with jquery/ajax form submission functionality

I followed a jQuery code for form submission that I found on various tutorial websites, but unfortunately, the ajax functionality doesn't seem to be working. When I try to submit the form, nothing happens at all. I've tried troubleshooting in eve ...

Comparing jQuery AJAX with UpdatePanel

Our team is facing the challenge of dealing with a page containing an overwhelming amount of jQuery code (specifically around 2000 lines) that has become difficult to maintain. We are considering shifting some of this functionality to the server side for ...

Displaying a page with dynamic data fetched from the server-side to be utilized in the getInitialProps method of

As a newcomer to next.js, my goal for my project is to connect to a database, retrieve data, process it using express, and then utilize it on the client side of my application. I plan to establish a connection to the database within the express route han ...

Display the debugging result of the textarea JavaScript input in the innerHTML paragraph as "undefined"

I have been working on a code editor and I almost have everything functioning properly. I can type text into the textarea and then press a button to load a function, which displays the result of the code in the web browser console. I am attempting somethin ...

Checking the status of an object using a Jasmine spy call in an Ajax method

Currently, I am unit testing an Angular controller that relies on a Rails Resource factory to manage data exchange with a Rails application. Specifically, POST requests are handled by calling a method on the model, like so: $scope.resource.update().then(s ...

The service worker is sending out a pair of requests

I have successfully set up a service worker to cache all requests for offline use, but I am experiencing a problem. Every time I load a page, two requests are hitting my webserver: one from the service worker and one from the browser! How can I cache the ...

HTML5 video displaying remaining time before something happens

After troubleshooting, I was able to resolve the issue by implementing the following code: $oVideo.bind('timeupdate', function() { var currVideo = document.getElementById("vPlayer"); var iNow = currVideo.currentTime; var countdown = eval(currVid ...

Steps to incorporate a JavaScript component for the HTML Header (navbar) across a website containing over 100 webpages

Managing a website with 200+ webpages and a Navigation Bar (Header) can be a challenge. How do I automate this process to avoid updating the header in each of the 200+ webpages using JavaScript? What's the most effective approach? I tried implementin ...