String#gsub 弄乱了替换?

String#gsub messing up the replacement?

我正在尝试用外部内容即时替换页面的一部分。

这里是 source.html:

<!DOCTYPE html>
<html>
  <head>
    <%= foobar %>
  </head>
  <body>
    This is body
  </body>
</html>

和替换字符串 inject.js:

var REGEXP  = /^\'$/i; var foo = 1;

一个 ruby 代码,通过组合两者输出一个文件。

pageContent = File.read('./source.html')
jsContent = File.read('./inject.js');
output = pageContent.gsub("<%= foobar %>", jsContent)
File.open('./dest.html', "w+") do |f|
  f.write(output)
end

但是,由于 inject.js 中的 \',我搞砸了 dest.html

<!DOCTYPE html>
<html>
  <head>
    var REGEXP  = /^
  </head>
  <body>
    This is body
  </body>
</html>$/i; var foo = 1;
  </head>
  <body>
    This is body
  </body>
</html>

如何解决这个问题?

尝试使用 gsub 块形式:

output = pageContent.gsub("<%= foobar %>") { jsContent }

This one 在这种情况下可以帮助您。

你能试试%q{jsContent}类似的东西吗?