2016-07-30 91 views
-1

我試圖用動態外部內容替換頁面的一部分。String#gsub搞亂了替換?

這裏是source.html

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

和替換字符串inject.js

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

通過組合兩個文件輸出A紅寶石代碼。

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> 

我該如何擺脫這個問題?

回答

1

嘗試使用gsub塊的形式:

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

0

This one可以幫助你在這種情況下。

你可以試試%q{jsContent}這樣的事情。