【问题标题】:How can I replace strings between <!-- comment --> with something else如何将 <!-- comment --> 之间的字符串替换为其他内容
【发布时间】:2019-06-22 06:46:22
【问题描述】:

我正在使用 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("(?

【问题讨论】:

  • Gulp 真的很穷。浏览 Webpack 教程。
  • 现在不是更换这个工具的时候......

标签: javascript regex gulp


【解决方案1】:

假设您始终保持开始和结束 cmets 中的文本相同,这可行:

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 构造函数的结果,例如 @ 987654326@


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

【讨论】:

    猜你喜欢
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多