求助!想要使用node动态替换html文件的title,但是fs读取html后的字符串不能使用正则。

新手上路,请多包涵

想要使用nodefs模块读取html,然后再利用正则来修改htmltitle,但是fs读到的字符串不能使用正则,是个多行字符串。


代码如下:

///app.js

let testHtml = fs.readFileSync('./test.html', 'utf8')
testHtml.replace(/<title>([\s\S]){1,}<\/title>/gm, '<title>二标题</title>')
fs.writeFileSync('./src/test.html', testHtml, 'utf8')

///test.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>一标题</title>
</head>
<body>
</body>
</html>

最后test的标题并没有改变,正则没有效果。
求助啊,大佬们

阅读 5.4k
1 个回答

改一下,你忘了赋值了

testHtml = testHtml.replace(/<title>([\s\S]){1,}<\/title>/gm, '<title>二标题</title>')
推荐问题