Reputation: 2357
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.
Upvotes: 1
Views: 1975
Reputation: 141
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"
Upvotes: 1
Reputation: 1197
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
Upvotes: 0
Reputation: 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>
Upvotes: 1