Using Javascript regex to capture the image name from a CSS file

As I work with JavaScript regex, my goal is to extract the image name and extension as a capture group of CSS properties.

Criteria

  • Must start with "url"
  • Followed by brackets
  • Optional quotes inside brackets
  • The location can include path information
  • Must end with jpeg, jpg, gif, or png

For example:

behavior: url(#default#VML);                   -> Wrong ending, so ignored
background-image: url(dog.ttf);                -> Wrong ending, so ignored
background-image: url('cat.png');              -> cat.png
background-image: url(bird.gif);               -> bird.gif
background-image: url('../monkey.png');        -> monkey.png
background-image: url('../../rab$bit.png');    -> rab$bit.png
background-image: url('../animal/cow.jpg');    -> cow.jpg

This is what I have come up with so far:

url(?:\(\"|\(\'|\(\/?.*\/|\()(\.+)?(\/.*\/)?(\w*)+(.png|.jpg|.gif|.jpeg)

https://i.sstatic.net/6kXH5.png

https://regex101.com/r/3mMdTI/6

Unfortunately, due to the '\w' group, this regex breaks when a filename includes digits or special characters like $. Can anyone suggest a better solution?

Answer №1

It seems like you're inquiring about extracting image names with format only, excluding the path and other details.

var text = `behavior: url(#default#VML);                   
background-image: url(dog.ttf);                
background-image: url('cat.png');              
background-image: url(bird.gif);               
background-image: url('../monkey.png');        
background-image: url('../../rab$bit.png');    
background-image: url('../animal/cow.jpg');`

var output = text.match(/[\w\.\$]+(?=png|jpg|gif)\w+/g)

console.log(output)

Answer №2

Here is a suggestion for you:

let regex = /([^\/('"\\]+)\.(jpg|png|jpeg|gif)/i

I have included all characters in the square brackets that should not be present in the image name /, \, ', ", (. Feel free to adjust this regex pattern based on your requirements.

Answer №3

give this a shot:

(.*\/)?(.*?\.(png|jpg|jpeg|gif)$)

The second group will capture the image file name.

Answer №4

Give this a shot:

let text = `check this out: 
<div>
var string = `behavior: url(#default#VML);
background-image: url(home_bbbbbb_14.ttf);
background-image: url('home.ttf');
background-image: url('home.png');
background-image: url(images/home_bbbbbb_14.png);
background-image: url('images/home_bbbbbb_14.jpeg');
background-image: url("images/home_bbbbbb_14.png");
background-image: url(home_bbbbbb_14.png);
background-image: url('home_bbbbbb$_14.png');
background-image: url("home_bbbbbb_14.png");
background-image: url("../img/home_bbbbbb_14.png");
background-image: url("./img/home_bbbbbb_14.png");
background-image: url("../../img/home_bbbbbb_14.jpg");
url("images/animated-overlay.gif");
url("images/ui-bg_flat_75_ffffff_40x100.png");
url('select2.png');
url(select2x2.png);
url('../images/back_enabled.png');
url('../pic/back_enabled.png');`

var result = string.match(/(?!url)([^\/('"\\]+)\.(?=png|jpg|gif|jpeg)('|"|)\w+/g)

console.log(result)

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

Fill in according to the options selected in the dropdown menu

Recently delving into the world of React, I encountered a design challenge that needs solving. My goal is to have a selection field with various choice values, each offering different sets of KPIs and UOMs. Depending on the chosen value, I should be able t ...

Create a function that adds a new div element with a one-of-a-kind identification when

I am currently developing a web application on www.firstusadata.com/cash_flow_test/. The functionality involves two buttons that add products and vendors dynamically. However, the issue I'm facing is that the appended divs do not have unique IDs, maki ...

Incorporating an offset with the I18nPluralPipe

Having trouble with my multiselect dropdown and the text pluralization. I attempted to use the I18nPluralPipe, but can't seem to set an offset of 1. ListItem = [Lion, Tiger, Cat, Fox] Select 1 Item(Tiger) = "Tiger", Select 3 Item(Tiger, Cat, Fox) = ...

Guide to setting the hiddenfield value within a listview using javascript or jquery

Here is the javascript code that I am using to retrieve the value from my textbox with autocompleteextender. <script type="text/javascript"> function txt_lect_in_AutoCompleteExtender_itemSelected(sender, e) { var hdEmpId = $get('& ...

An option selection component for Vue.js

I'm attempting to design a component like the following: <template> <option v-for="(text, value) in options" :value="value"> {{ text }} </option> </template> Unfortunately, I encountered an error me ...

transforming a div to behave similarly to an iframe

I am trying to load content from my page into a div element using the following function: function loadmypage(DIV, pageURL) { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } e ...

"Adding an Image within a Textbox Using Ext JS: A Step-by-Step

How can I add a search image inside a textbox created with the following code? I have created a table with a footer, and within one of the textboxes in the table, I want to include a search button that will call another function when clicked. However, desp ...

unable to use ref to scroll to bottom

Can someone explain to me why the scroll to bottom feature using ref is not functioning properly in my code below? class myComponent extends Component { componentDidMount() { console.log('test') // it did triggered this.cont ...

What is the best way to determine the value of margin-left in inline CSS using jQuery?

Here is the code snippet I am working with: <div class="ongoing" style="width: +728px; margin-left: +12480px"> I need to extract the value of the margin-left property for scrolling purposes. The technique I used to retrieve the width value does no ...

Is it acceptable to manipulate the prevState parameter of the setState function as mutable?

It is commonly known that directly modifying this.state is not recommended, and instead setState should be used. Following this logic, I assumed that prevState should also be treated as immutable, and setState should always involve creating a new object i ...

What is the best way to utilize jspdf for formatting data, specifically when wanting the first column to be in bold?

How can I customize data formatting using jspdf? Specifically, I would like the first column to be in bold and the second column in normal text. Additionally, I want to align them in the middle of the pdf output with different colors for each column. Belo ...

In the realm of React Native, an error arises when attempting to access 'this._nativeModule.isBluetoothEnabled', as the reference to null prevents it from

Recently, I delved into working with react native and attempted to incorporate react-native-bluetooth-classic into my project. The URL for the API overview can be found here. However, I encountered an issue that has me stuck: "TypeError: null is not ...

Images are failing to load in Ionic 3

Currently working on developing an Ionic application and troubleshooting the use of the camera native plugin. The script functions flawlessly in a fresh project, but encounters issues within the current project environment. Initially suspected a problem w ...

How can I incorporate dynamic fields into a Typescript type/interface?

In my Typescript interface, I have a predefined set of fields like this: export interface Data { date_created: string; stamp: string; } let myData: Data; But now I need to incorporate "dynamic" fields that can be determined only at runtime. This me ...

What is the process for moving entered data from one text box to another text box when a checkbox is selected?

I need help with a function that reflects data entered in one text box to another text box when a checkbox is ticked. The checkbox is initially checked and the values should change when it is unchecked and then checked again. Currently, the code is only ou ...

Unpredictable jQuery Ajax setTimeout

I have a script that retrieves data from ajax.php and displays it in a div. The intention is for the information to be shown for a period of 3 seconds before hiding the #ajax-content and displaying #welcome-content. Most of the time it works as intended, ...

Sorting elements in an array using jQuery is a common task that can be easily accomplished

Query: I am faced with a challenge in handling a table where rows are dynamically added upon button clicks. To allow users to rearrange the rows, I have incorporated the jquery-ui sortable() function for sorting purposes. Consider the following scenario: ...

What is causing these dynamic carousels to malfunction in Chrome?

After using Agile Carousel successfully for a while, I am now experiencing issues with it not working properly in Safari and Chrome, although it functions fine on Firefox and Safari for iPad. On this specific page, the carousel stops at the second image, ...

Distinguishing between a regular JavaScript variable and one annotated with a dollar sign

Many responses have addressed the question of using a dollar sign in JavaScript variables. In essence, the dollar sign functions as an identifier in JavaScript variables. However, I am curious if there are other distinctions between regular variables and ...

Accessing PHP variables within a React componentTo access external

How can I pass the id selected in a menu from a react component to a PHP file, after already knowing how to send data from PHP to the react component? $.ajax({url: '/file.php', type: 'POST', dataType: 'json', ...