Get relative path from $().css(“background-image”)

511
November 23, 2016, at 9:29 PM

In the CSS I have background-image: url(folder/bg.jpg);.

For this, JQuery's css("background-image") returns url(http://www.example.com/folder/bg.jpg),

but I need folder/bg.jpg only.

I'm looking for a regex that would solve this for me.

Answer 1

Try using String.prototype.split() with RegExp /\//, Array.prototype.join() , String.prototype.slice()

$("div").html( 
   
  $("div").css("backgroundImage").split(/\//) 
  .slice(-2).join("/").slice(0, -1) 
 
)
div { 
  background-image: url(http://www.example.com/folder/bg.jpg) 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> 
</script> 
<div></div>

Answer 2

I know this is not the best regex to all cases, but you get the point.

/* Explaining:
/ regex here /
[^\/]+  ---> will match anything before a / (https:)
\/\/    ---> the // after https: 
[^\/]+  ---> will match anything before / (www.example.com)
\/      ---> will match /
(.*)    ---> the rest of url (that you want)
So, you need to get the [1] index of the returned array.
*/ 
"http://www.example.com/folder/bg.jpg".match(/[^\/]+\/\/[^\/]+\/(.*)/)[1]

Will return: "folder/bg.jpg"

Answer 3

Since jQuery will return the absolute path, you will never be able to determine the relative path without string manipulation knowing what to remove given how nested your page may be in your directory hierarchy. I would recommend string replace with Regex. See plnkr below.

    $("div").click(function() {
        var bg = $(this).css('background-image');
        bg = bg.replace('url(http://run.plnkr.co/cybkjF7HN9sYH3oS/','').replace(')','');
        alert(bg);
    });

http://plnkr.co/edit/zkeoRE?p=preview

Rent Charter Buses Company
READ ALSO
Options on a select changed with jquery but strange results with Chrome

Options on a select changed with jquery but strange results with Chrome

I have this site - http://kingsberryfuels. com/ - which, if you visit on a chrome browser and select gas oil as a fuel type then with jquery I'm changing the options in the select below.

350
Combine CSS + jQuery animation

Combine CSS + jQuery animation

This question is quite hard to explain. But I have around 10 seconds of animation on my website that happens from time to time.

435
jquery close element after element and re open new element

jquery close element after element and re open new element

I have one big UL of inline list items containing input check boxes. .

462