Luke
Luke

Reputation: 3046

replace relative path with a regular expression on asyncronously loaded css

I'm asyncronously loading a css.

@font-face{
    src: url('fonts/le-havre-1_300_normal-webfont.eot');
    src: url('fonts/le-havre-1_300_normal-webfont.eot?#iefix') format('embedded-opentype'),
    url('fonts/le-havre-1_300_normal-webfont.woff') format('woff'),
    url('fonts/le-havre-1_300_normal-webfont.ttf') format('truetype'),
    url('fonts/le-havre-1_300_normal-webfont.svg#LeHavreLight') format('svg');
}

I have to replace the path dynamically, for example:

url(' -> url('http://www.site.com/skin/light/

I wrote this regular expression but it seems to replace only the first value.

var newCss = cssText.replace(/url\(\'(.+)\'\)/g, function(a,b){
    return 'url(\''+'http://www.site.com/skin/light/' + b + '\')';
});

How can I replace all the url attributes?

Upvotes: 0

Views: 739

Answers (2)

Dor
Dor

Reputation: 7504

The regexp/url\(\'(.+?)\'\)/g solves the problem, because of the un-greediness of the expression .+?, in contrast to the greedy expression .+ that matches to the entire following string
(if multi-line enabled):

url('fonts/le-havre-1_300_normal-webfont.eot');
src: url('fonts/le-havre-1_300_normal-webfont.eot?#iefix') format('embedded-opentype'),
url('fonts/le-havre-1_300_normal-webfont.woff') format('woff'),
url('fonts/le-havre-1_300_normal-webfont.ttf') format('truetype'),
url('fonts/le-havre-1_300_normal-webfont.svg#LeHavreLight') format('svg')

See the "U (PCRE_UNGREEDY)" modifier: Pattern Modifiers @ php.net

Upvotes: 0

gpojd
gpojd

Reputation: 23085

Try the /m modifier too. Since the string has multiple lines, it probably needs it.

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

Upvotes: 1

Related Questions