Search code examples
javascriptregexgulp

How can I replace strings between <!-- comment --> with something else


I am using gulp to facilitate my frontend deployment. I would like to replace some strings in index.html For example, turning the following code like

<!-- js starts -->
<script src="xxxxxx/xxxx/xxx1.js"></script>
<script src="xxxxxx/xxxx/xxx2.js"></script>
<script src="xxxxxx/xxxx/xxx3.js"></script>
<script src="xxxxxx/xxxx/xxx4.js"></script>
<!-- js ends -->

into

<!-- js starts -->
<script src="xxxxxx/xxxx/all-one.js"></script>
<!-- js ends -->

I have installed gulp-string-replace, and it works fine with some simple regular expression. But my case seems contains some special characters, such as < ! -- >

This is my gulp code but not implemented what I want. gulp.src('index.html').pipe( replaceString("(?<='')(.*)(?='')", "what I want") ).pipe( gulp.dest(target) );


Solution

  • Assuming that you always keep the text in the start and end comments the same, this works:

    var gulp = require('gulp');
    var replaceString = require('gulp-string-replace');
    
    let replacement = 'Hello world!';
    let pattern = /(<!-- js starts -->)[^!]+(<!-- js ends -->)/gim;
    
    gulp.src('index.html')
        .pipe(replaceString(pattern,function(n0,n1,n2){
            return n1 + '\n' + replacement + '\n' + n2;
        }))
        .pipe(gulp.dest('output'));
    

    Result of output/index.html:

    <!-- js starts -->
    Hello world!
    <!-- js ends -->
    

    By the way, you said you were trying to use Regex, but it looks like you were passing in a string literal, not a Regex literal (what I use above), or the result of calling the RegExp constructor, like var pattern = new RegExp('hello\s{0,1}World');


    Although I won't give advice on what you should and shouldn't use, I will point out that gulp-string-replace has not been updated for a while, and has an open issue that actually affected my answer; I tried to use inline back-references (e.g. $1\nHello World\n$2) and it did not work, forcing me to use the callback function argument. gulp-string-replace just uses replacestream for the actual replacement operation.