Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get background image URL without the quotes? [duplicate]

I'm trying to use jQuery to get the background image URL of a div but without any quotes.

So basically all I need is the URL/Path to the image.

I'm using the code bellow but this code gives me a URL like this:

"http://somesite.com/images/apple.png"

As you can see, it will place the URL between double quotes which is not what I want.

Here is the code:

var bg = $('.selected').css('background-image');
bg = bg.replace('url(','').replace(')','');

alert(bg);

could someone please advise on this issue?

like image 201
rooz Avatar asked Apr 17 '16 12:04

rooz


2 Answers

Replacing with RegEx /"/g will give me what you want:

alert(
  '"http://somesite.com/images/apple.png"'
    .replace(/"/g, "")
);
like image 51
Praveen Kumar Purushothaman Avatar answered Nov 08 '22 23:11

Praveen Kumar Purushothaman


There are several ways

var bg_img = $('body').css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1');

var bgImage = $('#content').css('background-image').replace(/^url|[\(\)]/g, '');

These stack overflow qns can help you

Get URL from background-image Property

like image 36
OmarJ Avatar answered Nov 09 '22 00:11

OmarJ