0

if my html is

<div style="background-image: url(http://domain.com/randompath/random4509324041123213.jpg);"></div>

And I get style attribute like..

var img_src = $('div').css('background-image');

So output is

url("http://domain.com/randompath/random4509324041123213.jpg")

Any regex or some basic thing to find image src/path 100% ? like

http://domain.com/randompath/random4509324041123213.jpg

100% I mean cross browser, It should work 100%

I not sure about output from var img_src = $('div').css('background-image'); has pattern like this in all browsers , If "yes" so I can do .replace()function

Playground : http://jsbin.com/apalat/1/edit

3
  • Why would you need a regex for this? Why not just fetch the element's background-image property? Commented Mar 14, 2013 at 11:20
  • Sorry sorry Edited , I want pure image src like http://domain.com/randompath/random4509324041123213.jpg @Pekka웃 Commented Mar 14, 2013 at 11:20
  • Can you guarantee that someone has not written background-image: url('http://domain.com/randompath/random4509324041123213.jpg');" with the URL surrounded by quotes? It is valid CSS to have quotes around a URL - they are optional in the specification. Commented Mar 14, 2013 at 13:55

2 Answers 2

3

Try this one:

$("code").html(img_src.slice(5, -2));

CHECKOUT FIDDLE

Update:

For 'chrome' because chrome doesn't add '"' quotes:

var img_src = $('div').css('background-image');

$("code").html(img_src.slice(5, -2));

if (navigator.userAgent.toLowerCase().indexOf('chrome') >= 0) {
   $("code").html(img_src.slice(4, -1));
}

UPDATED FIDDLE

Sign up to request clarification or add additional context in comments.

7 Comments

Is my img_src will output like url("http://domain.com/randompath/random4509324041123213.jpg") in all browsers right ?
Oh yes yes. This seems to be.
In Chrome 23, your fiddle shows ttp://domain.com/randompath/random4509324041123213.jp as output.
Yes in chrome will show url(http://domain.com/randompath/random4509324041123213.jpg)
Because in Firefox img_src = url("http://domain.com/randompath/random4509324041123213.jpg") (Firefox added some quotes) and in Chrome it is url(http://domain.com/randompath/random4509324041123213.jpg) so the slicing is wrong
|
1

Don't need regex, just cut the string...

http://jsfiddle.net/BHcsQ/2/

var s = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
var s_sub = s.substring(5, s.length-2);

alert(s_sub);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.