4

gulp-replace 0.5.4

Current via gulp and rev:

<link rel="stylesheet" href="assets/styles/app-3c224ff086.css">

Goal:

<link rel="stylesheet" href="assets/styles/app-3c224ff086.css" media="screen">

Result:

<link rel="stylesheet" href="$1" media="screen">

Initial test was: https://regex101.com/r/miM7TN/1 . I might have linked the test with a capture group of $0, but in my project I am using capture group 1.

In my gulp task the following is added:

var regex = /\"assets\/styles\/app-+.*\"/;
var subst = `$1 media="screen"`;
.pipe(replace(regex, subst))

My string, to include start and end quotes, is being found. Instead of a capture group I am getting a literal $1. How do I get the actual value of the capture group? The gulp-replace documentation shows a replace value '$1foo'. Similar questions on SO show '$1' and "$1", and I am not yet seeing the difference to my situation. I've tried back-ticks, single quotes, and double quotes.

Dave
  • 84
  • 9
  • 1
    `$1` refers to a capturing group with ID=1, the first `(...)`. You must use `var regex = /("assets\/styles\/app-+.*")/;` for `$1` to "work" the same way as `$&` (backreference to the whole match value) (or `$0` in the recent browser versions). Or, yes, try to replace `$0` with `$&` in your current replacement pattern. – Wiktor Stribiżew Mar 08 '17 at 07:52
  • 1
    Btw, regex101 does not recognize the valid `$&` JS backreference, it is a [bug](https://github.com/firasdib/Regex101/issues/777). Test in the target environment only. – Wiktor Stribiżew Mar 08 '17 at 07:55
  • @WiktorStribiżew Thank you. Adding the () before and after the /" fixed it. – Dave Mar 08 '17 at 13:33

2 Answers2

1

The $1 backreference refers to a capturing group with ID 1, the text captured with the first (...) in your pattern.

You must use

 var regex = /("assets\/styles\/app-+.*")/;

for $1 to "work" the same way as $& (backreference to the whole match value).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

Your can use a callback as the second parameter in gulp-replace. The function was loop over each capture group. Here's an example where I am converting camelCase variables to css notation

.pipe(replace(/([A-Z])/g, function(match){
  return '-'+match.toLowerCase()
}))

{camelCase1: 1, camelCase2: 2}

Becomes camel-case1 and case-case2

Dave Keane
  • 729
  • 8
  • 19