String#gsub弄乱了替换?

时间:2016-07-30 08:26:49

标签: ruby gsub

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

以下是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

但是,由于dest.html中的\',我发生了混乱inject.js

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

如何摆脱这个问题?

2 个答案:

答案 0 :(得分:1)

尝试使用gsub阻止形式:

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

答案 1 :(得分:0)

在这种情况下,

This one可以为您提供帮助。

请你试试%q{jsContent}这样的事情。

相关问题