Escaping an Issue with Grunt "string-replace" Bookmark

Since I started using Grunt, I have found more and more cases where Grunt tasks turn out to be very useful and a huge timesaver. That is, timesaver once you got whatever you’re trying to do up and running. In the most recent case, I ran into an issue with using Grunt string-replace to replace background-image URLs in my CSS file with a different path to prepare them for use with Rails" asset pipeline.

I needed to search for : url(img/imagename) to then be replaced with : url(<%= asset_path 'img/imagename' %>).

As the first replacement pattern I used ':$1url(<%= asset_path \'$2$3\' %>)’. This failed with an error message. Since I was using the < & > characters in the pattern, I figured these characters might need to be escaped.

I tried ':$1url(\<%= asset_path \'$2$3\' %\>)’ and various variations, all without any luck. Eventually I found a hint on Stack Overflow, that this might not work this way at all and needs to be processed with two passes.

After checking back with the author of string-replace, this problem seems to be related to Lo-Dash's template security.

The final working code looks like this now and works pretty much as well as it would with running it in one pass, I believe.

  'string-replace': {
    inline: {
      files: {
        'dist/css/app.css.erb': ['css/app.css'],
      options: {
        replacements: [{
          pattern: /:(\s*)url\((img)(.+?)\)/ig,
          replacement: ':$1url(\<%= asset_path \'$2$3\' CLOSETAG)'
          pattern: /CLOSETAG/g,
          replacement: '%>'

Leave a comment

Available formatting commands

Use Markdown commands or their HTML equivalents to add simple formatting to your comment:

Text markup
*italic*, **bold**, ~~strikethrough~~, `code` and <mark>marked text</mark>.
- Unordered item 1
- Unordered list item 2
1. Ordered list item 1
2. Ordered list item 2
> Quoted text
Code blocks
// A simple code block
// Some PHP code
[Link text](
Full URLs are automatically converted into links.

Replied on your own website? Send a Webmention!