开发者

Chrome & Firefox interpret url() differently, making .replace() regex challenging

The following needs to remove url(' portion of string, previously returned from .css('background-image') on an element object in the DOM, which works perfectly well in Firefox, but 开发者_JS百科not in Chrome.

// example value of artworkURL: url('http://somewebsite/picture.jpg')
artworkURL = artworkURL.replace(/url\(\'/g,'');

I discovered this was because Chrome removes the '' from url('picture.jpg') however, removing \' from the regular expression causes Firefox to then break, because Firefox replaced '' with "" but still understands the regular expression. Even the removal of parenthesis in the CSS causes Firefox to render "" back in.

How do I keep both browsers and their various compliance happy?


Try:

artworkURL = artworkURL.replace(/url\(['"]?/g,'');

This will remove the ' if it it present, and even takes into account browsers that might use " instead. A similar regex can be used for removing the end:

artworkURL = artworkURL.replace(/['"]?)/g,'');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜