nmac
nmac

Reputation: 680

Parsing CSS background attribute

I am having trouble matching a specific pattern in a backgroundImage css expression. I want to get the u/user/rest/of/stuff out of "url(foo/bar/u/user/rest/of/stuff)". However I am not sure how to get only the second u (the u in url would be the first), plus everything after that up to the second parenthesis.

Upvotes: 0

Views: 59

Answers (2)

Broco
Broco

Reputation: 217

For I produce a lot of typos in regex and for better readability I use functions whenever possible for this kind of stuff...

function GetSubstring(str, from, to) {
    return str.substring(str.lastIndexOf(from)+from.length,str.lastIndexOf(to));
}

And then use

GetSubstring('url(foo/bar/u/user/rest/of/stuff)','url(foo/bar/',')');

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

Use word boundary(\b) ,

> "url(foo/bar/u/user/rest/of/stuff)".match(/\bu\b[^)]*/g);
[ 'u/user/rest/of/stuff' ]

OR

Use a look-ahead (?=...)

> "url(foo/bar/u/user/rest/of/stuff)".match(/u[^()]*(?=\))/g);
[ 'u/user/rest/of/stuff' ]

Upvotes: 1

Related Questions