javascriptregexgulp-replace

How to use a Capture Group with gulp-replace?


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.


Solution

  • 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).