【问题标题】:replace escaped " with escaped ' in ruby string在 ruby​​ 字符串中用转义的 ' 替换转义的 "
【发布时间】:2014-08-25 08:31:04
【问题描述】:

我有一个包含许多转义双引号 \" 的 ruby​​ 字符串,我想用转义单引号 \' 替换它,但我不知道该怎么做。

我一直在尝试使用 gsub,但是类似 mystring.gsub('\\"', '\\'') 的东西不起作用。

以下字符串的(部分)示例 - 我的问题是我不想替换所有双引号,只替换转义的...

仅供参考,注入的脚本在包含为 src 时可以正常工作,但我正在动态拉取内容并在视图中注入脚本:

而不是

<script src='...'></script> 

我在做

<script><%=raw @mystring%></script>

....

document.write("<div class=\"fsBody fsEmbed\">"+"\n");
document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.formstack.com/forms/css/3/reset.css?20140508\" />"+"\n");
document.write("    <link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.formstack.com/forms/css/3/default.css?20140519\" />"+"\n");
document.write("    "+"\n");
document.write("<!--[if IE]>"+"\n");
document.write("    <link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"https://www.formstack.com/forms/css/3/ie.css?20140508\" />"+"\n");
document.write("<![endif]-->"+"\n");
document.write("<!--[if IE 7]><link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"https://www.formstack.com/forms/css/3/ie7.css\" /><![endif]-->"+"\n");
document.write("<!--[if IE 6]><link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"https://www.formstack.com/forms/css/3/ie6fixes.css\" /><![endif]-->"+"\n");
document.write("    <style type=\"text/css\">"+"\n");
document.write("        "+"\n");
document.write("    .fsBody .fsForm, .fsForm .fsSpacerRow .fsRowBody {"+"\n");

有人可以帮忙吗?

【问题讨论】:

  • 你确定他们逃脱了吗?在某些情况下,Rails 会以"\" 开头渲染它们,例如当您inspect 一个变量或在irb 中输出它时。
  • 如果他们被转义,试试这个:mystring.gsub('\\"', '\\\'')。您首先必须转义斜杠,然后转义引号。
  • @Adam - 使用单引号时不需要转义` or "`。只需转义'\` if proceeding '`。
  • 绝对转义 - 这是使用 的字符串输出示例(将插入到原始问题中)

标签: ruby string


【解决方案1】:

他们很可能没有逃脱。这就是当您在它们上执行 inspect 时 ruby​​ 显示带引号的字符串的方式(控制台默认执行检查以显示命令的结果)。试试:

mystring.gsub('"', "'")

【讨论】:

    【解决方案2】:

    最后,我最终使用了预渲染服务器来预渲染页面并包含脚本的内容。

    如果脚本是从 src url 中包含的,它可以工作,但如果我尝试拉入源代码并将其包含在标签之间的页面中,它将无法工作。

    使用预渲染允许我在服务器端运行脚本并生成页面,然后将完成的部分返回给浏览器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 2015-10-26
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      相关资源
      最近更新 更多