2

Any working Regex to find image url ?

Example :

var reg = /^url\(|url\(".*"\)|\)$/;

var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';

var string2 = 'url(http://domain.com/randompath/random4509324041123213.jpg)';


console.log(string.match(reg));
console.log(string2.match(reg));

I tied but fail with this reg pattern will look like this, I just want image url between url(" ") or url( )

I just want to get output like http://domain.com/randompath/random4509324041123213.jpg

http://jsbin.com/ahewaq/1/edit

2
  • Are you just trying to extract the URL from the string? Commented Mar 14, 2013 at 14:21
  • I just want to get output like http://domain.com/randompath/random4509324041123213.jpg @JamesHill Commented Mar 14, 2013 at 14:22

3 Answers 3

1

I'd simply use this expression:

/url.*\("?([^")]+)/

This returns an array, where the first index (0) contains the entire match, the second will be the url itself, like so:

'url("http://domain.com/randompath/random4509324041123213.jpg")'.match(/url.*\("?([^")]+)/)[1];
//returns "http://domain.com/randompath/random4509324041123213.jpg"
//or without the quotes, same return, same expression
'url(http://domain.com/randompath/random4509324041123213.jpg)'.match(/url.*\("?([^")]+)/)[1];

If there is a change that single and double quotes are used, you can simply replace all " by either '" or ['"], in this case:

/url.*\(["']?([^"')]+)/
Sign up to request clarification or add additional context in comments.

Comments

1

Try this regexp:

var regex = /\burl\(\"?(.*?)\"?\)/;
var match = regex.exec(string);
console.log(match[1]);

The URL is captured in the first subgroup.

3 Comments

@l2aelba This is not a helpful comment. What is not working? Did you extract the first subgroup?
got ["url(http://domain.com/randompath/random4509324041123213.jpg)", "http://domain.com/randompath/random4509324041123213.jpg"]in console.log jsbin.com/ahewaq/5/edit
oh yeahhh !! 2 arrays inside ! sorry
-1

If the string will always be consistent, one option would be simply to remove the first 4 characters url(" and the last two "):

var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';

// Remove last two characters
string = string.substr(0, string.length - 2);

// Remove first five characters
string = string.substr(5, string.length);

Here's a working fiddle.

Benefit of this approach: You can edit it yourself, without asking StackOverflow to do it for you. RegEx is great, but if you don't know it, peppering your code with it makes for a frustrating refactor.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.