繁体   English   中英

我怎样才能替换之间的字符串<!-- comment -->用别的东西

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

我正在使用 gulp 来促进我的前端部署。 我想替换 index.html 中的一些字符串 比如把下面的代码变成这样

<!-- 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 -->

进入

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

我已经安装了 gulp-string-replace,它与一些简单的正则表达式一起工作得很好。 但是我的案例似乎包含一些特殊字符,例如 < ! -->

这是我的 gulp 代码,但没有实现我想要的。 gulp.src('index.html').pipe(replaceString("(?<='')(.*)(?='')", "我想要的") ).pipe(gulp.dest(target ) );

假设您始终将开始和结束评论中的文本保持不变,这将起作用:

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'));

结果output/index.html

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

顺便说一句,你说你正在尝试使用 Regex,但看起来你传入的是一个字符串文字,而不是一个 Regex 文字(我上面使用的),或者调用 RegExp 构造函数的结果,比如var pattern = new RegExp('hello\\s{0,1}World');


虽然我不会就您应该和不应该使用什么提供建议,但我会指出gulp-string-replace已经有一段时间没有更新了,并且有一个实际影响我的答案的未决问题; 我尝试使用内联反向引用(例如$1\\nHello World\\n$2 )但它不起作用,迫使我使用回调函数参数。 gulp-string-replace只是使用replacestream进行实际的替换操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM