0

My code seems to be returning a null value for my image url. I would like to get just the link, but it does not seem to work.

Here is my code:

var image_url = jQuery('#bgImgWrap').css('background'), image;

// Remove url() or in case of Chrome url("")
image_url = image_url.match(/^url\("?(.+?)"?\)$/);

Here is what it returns right after the image_url is declared:

Image: rgb(255, 255, 255) 
 url(http://localhost:8000/mysite/images/Our_Services2.jpg) 
no-repeat scroll 0% 0% / cover padding-box border-box 

Here is what is returned after my regex is used:

Image: null

I am not that great with regex, but i was wondering if someone would be able to help me accomplish getting the correct background image url that i need? Thank you!

2
  • Generally speaking, when writing a regex, "active-tester" tools tend to help me, constantly highlighting in sample data what your regex will match. One I use is Regexpal.com Commented Apr 25, 2014 at 17:24
  • @MikeSamuel Actually, no, that appears to be optional based on the ?s afterward. Commented Apr 25, 2014 at 17:28

2 Answers 2

2

^ and $ in your regex /^url\("?(.+?)"?\)$/ makes it impossible to match. These metacharacter tells regex engine to match from beginning and ending respectively. But your url is not anchored at beginning or end. The correct regex would be.

/url\([^)]+\)/

also note .match will return an array of matched texts. So you need to access them by index.

image_url = image_url.match(/url\([^)]+\)/)[0];
Sign up to request clarification or add additional context in comments.

Comments

0

I think this issue has to do with the ^ and $ in your regex. You're testing it against a long several-line string that has your query in the middle, so you may want to just remove those.

IF you do want to be sure the result is on its own line, add \s* just after the ^, and before the $, so that you can account for some whitespace. (\s is whitespace, * means 0-any). You will also need to add an m after the final /, to specify that the regex should count those characters as "begin/end line", not "begin/end string"

So, the end regex, I believe, would be:

/^\s*url\(("?(.+?)"?\)\s*$/m

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.